prepareStatement为什么会空指针? 5
这里是全部代码,觉得都没有问题。可是调试出现空指针packageDBConnect;importjava.sql.*;publicclassDBConnect{Conne...
这里是全部代码,觉得都没有问题。可是调试出现空指针
package DBConnect;
import java.sql.*;
public class DBConnect {
Connection conn = null;
PreparedStatement pstmt = null;
public DBConnect(String sql)throws SQLException{
init();
this.prepareStatement(sql);
}
void init(){
try{
Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
Connection conn=DriverManager.getConnection("proxool.mysql");
}catch(Exception e){
e.printStackTrace();
}
}
public void prepareStatement(String sql)throws SQLException{
pstmt = conn.prepareStatement(sql);
}
public ResultSet executeQuery()throws SQLException{
if(pstmt!=null){
return pstmt.executeQuery();
}
return null;
}
public void executeUpdate()throws SQLException{
if(pstmt!=null){
pstmt.executeUpdate();
}
}
public void close()throws SQLException{
if(pstmt!=null){
pstmt.close();
pstmt=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}
public void setString(int index,String value)throws SQLException{
pstmt.setString(index, value);
}
public void setInt(int index,int value)throws SQLException{
pstmt.setInt(index, value);
}
public static void main(String args[])throws SQLException{
String sql = "select * from news";
DBConnect dbc = new DBConnect(sql);
ResultSet rs = dbc.executeQuery();
while(rs.next()){
System.out.print(rs.getString("name"));
}
}
} 展开
package DBConnect;
import java.sql.*;
public class DBConnect {
Connection conn = null;
PreparedStatement pstmt = null;
public DBConnect(String sql)throws SQLException{
init();
this.prepareStatement(sql);
}
void init(){
try{
Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
Connection conn=DriverManager.getConnection("proxool.mysql");
}catch(Exception e){
e.printStackTrace();
}
}
public void prepareStatement(String sql)throws SQLException{
pstmt = conn.prepareStatement(sql);
}
public ResultSet executeQuery()throws SQLException{
if(pstmt!=null){
return pstmt.executeQuery();
}
return null;
}
public void executeUpdate()throws SQLException{
if(pstmt!=null){
pstmt.executeUpdate();
}
}
public void close()throws SQLException{
if(pstmt!=null){
pstmt.close();
pstmt=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}
public void setString(int index,String value)throws SQLException{
pstmt.setString(index, value);
}
public void setInt(int index,int value)throws SQLException{
pstmt.setInt(index, value);
}
public static void main(String args[])throws SQLException{
String sql = "select * from news";
DBConnect dbc = new DBConnect(sql);
ResultSet rs = dbc.executeQuery();
while(rs.next()){
System.out.print(rs.getString("name"));
}
}
} 展开
2个回答
展开全部
你在init()中是这样写的Connection conn=DriverManager.getConnection("proxool.mysql");而不是赋值给全局变量conn,所以在调用prepareStatement(String sql)时conn会为空
更多追问追答
追问
这里多定义了一下。但是把init()里的Connection删除掉也不行,proxool连接池的配置是没有问题的。
追答
调试是conn为空吧 没有异常吗?
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询