2012-03-08 203 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()