有两个类:BaseDao是数据库连接类。AlbumDaoImpl类继承了BaseDao,实现了一个AlbumDao接口。在BaseDao中调用函数executeQuery()是返回正常的ResultSet,但是在AlbumDaoImpl类中调用后返回的ResultSet对象时空的!!!
这个是BaseDao中的函数
public ResultSet executeQuery(String sql,Object []params){
rs=null;
if(conn==null){
conn=getConnection();
}
else{
try {
presta=conn.prepareStatement(sql);
if(params!=null && params.length>0){
for(int i=0;i<params.length;i++){
presta.setObject(i+1, params[i]);
}
}
rs=presta.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rs;
}
这个是AlbumDaoImpl中的一个方法:
public void getAlbumList() {
String sql="select * from album";
Object []params={};
ResultSet res=null;
res=this.executeQuery(sql,params);
System.out.println(res);
try {
while(res.next()){
int id=res.getInt("id");
String artist =res.getString("Artist");
String title =res.getString("Title");
double price = res.getDouble("Price");
Date dateReleased = res.getDate("DateReleased");
String description = res.getString("Description");
System.out.println(id+"\t"+artist+"\t"+title+"\t"+price+"\t"+dateReleased+"\t"+description);
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{
this.closeResource();
}
}
一直报空指针异常!!!
在BaseDao中用同样的代码测试是有结果集的!!
public static void main(String[] args) {
Connection con=null;
BaseDao test=new BaseDao();
con=test.getConnection();
String sql="select * from album";
Object []params={};
ResultSet rs=null;
rs=test.executeQuery(sql,params);
System.out.println(rs);
try {
while(rs.next()){
int id=rs.getInt("id");
String artist =rs.getString("Artist");
String title =rs.getString("Title");
double price = rs.getDouble("Price");
Date dateReleased = rs.getDate("DateReleased");
String description = rs.getString("Description");
System.out.println(id+"\t"+artist+"\t"+title+"\t"+price+"\t"+dateReleased+"\t"+description);
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{
test.closeResource();
}
}
求解为什么?
When you execute, because conn is null, you only enter the branch to obtain the connection, and the statement to execute the query is not executed