ResultSet已关闭。为什么?

时间:2012-03-08 00:15:43

标签: java sqlite resultset

我遇到了一个小问题。我启动了我的应用程序,在启动查询并比较rs == null后,我收到错误ResultSet is closed

以下是代码:

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

4 个答案:

答案 0 :(得分:7)

您使用的方法不正确,以检查ResultSet是否有任何数据。

而不是

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

使用

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

答案 1 :(得分:3)

PreparedStatement.executeQuery()的{​​{3}}说:

  

“返回:包含查询生成的数据的ResultSet对象; 永不为空

测试空ResultSet的正确方法是调用ResultSet.hasNext()

答案 2 :(得分: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 :(得分: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(获取从数据库中提取的所有记录)