2012-03-08 107 views
0

我有一个小问题。我启动我的应用程序,并启动查询和比较rs == null后,我得到错误ResultSet is closedResultSet已关闭。为什么?

下面是代码:

error_code = NO_ERROR; 
    try 
    { 
     ArrayList <Harmonogram> al = new ArrayList <Harmonogram>(); 
     ResultSet rs = stat.executeQuery(myQuery); 
     if (rs == null) 
     { 
      return null; 
     }else{ 
      Harmonogram harm = new Harmonogram(rs.getLong(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getLong(5), rs.getString(6)); 

在此之后,我收到了SQLException告诉我:ResultSet is closed

回答

7

您正在使用错误的方法检查ResultSet是否有任何数据。

而不是

if (rs == null) 
{ 
    return null; 
} 

使用

if (! rs.next()) 
{ 
    return null; 
} 
1

我会做类似

error_code = NO_ERROR; 
try 
{ 
    ArrayList <Harmonogram> al = new ArrayList <Harmonogram>(); 
    ResultSet rs = stat.executeQuery(myQuery); 
    if (rs.next()){ 
     Harmonogram harm = new Harmonogram(rs.getLong(1), rs.getInt(2), rs.getInt(3),  rs.getInt(4), rs.getLong(5), rs.getString(6)); 
    }else{ 
     return null; 
    } 
}Catch... 

甚至while(rs.next()),如果你在ResultSet中试图循环(让所有的记录从数据库中提取)

2

以下是我会建议你把它写:

public class HarmonogramDaoImpl implements HarmonogramDao { 

    private static final String FIND_ALL_SQL = "SELECT * FROM HARMONOGRAM "; 

    // inject this with either a constructor or setter 
    private Connection connection; 



    public List<Harmonogram> findAllHarmonograms() throws SQLException { 
     List<Harmonogram> harmonograms = new ArrayList<Harmonogram>(); 

     PreparedStatement ps = null; 
     ResultSet rs = null; 

     try { 
      ps = this.connection.prepareStatement(FIND_ALL_SQL); 
      rs = ps.executeQuery(); 
      while (rs.hasNext()) { 
       Harmonogram harm = new Harmonogram(rs.getLong(1), rs.getInt(2), rs.getInt(3),  rs.getInt(4), rs.getLong(5), rs.getString(6));    
       harmonograms.add(harm); 
      } 
     } finally { 
      close(rs); 
      close(ps); 
     }   
     return harmonograms; 
    } 
} 

有留给你做什么或想一些事情,但是这是一个良好的开端。

3

javadocPreparedStatement.executeQuery()说:

“返回:包含由查询产生的数据的ResultSet对象; 永远不能为null

的正确的测试方法一个空的ResultSet是致电ResultSet.hasNext()