获取java.sql.SQLException:ResultSet关闭后不允许操作

当我执行下面的代码,我得到一个例外.我认为这是因为我正在准备新的声明与他相同的连接对象.我应该如何重写这个,以便我可以创建一个准备好的语句,并使用rs2?即使连接到相同的数据库,我必须创建一个新的连接对象?

    try 
    {
        //Get some stuff
        String name = "";
        String sql = "SELECT `name` FROM `user` WHERE `id` = " + userId + " LIMIT 1;";
        ResultSet rs = statement.executeQuery(sql);
        if(rs.next())
        {
            name = rs.getString("name");
        }

        String sql2 = "SELECT `id` FROM  `profiles` WHERE `id` =" + profId + ";";
        ResultSet rs2 = statement.executeQuery(sql2);
        String updateSql = "INSERT INTO `blah`............"; 
        PreparedStatement pst = (PreparedStatement)connection.prepareStatement(updateSql);    

        while(rs2.next()) 
        { 
            int id = rs2.getInt("id");
            int stuff = getStuff(id);

            pst.setInt(1, stuff);
            pst.addBatch();

        }

        pst.executeBatch();

    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }

private int getStuff(int id)
{

    try
    {   

            String sql = "SELECT ......;";
            ResultSet rs = statement.executeQuery(sql);

            if(rs.next())
            {
                return rs.getInt("something");

            }
            return -1;
    }//code continues
最佳答案
问题在于您在getStuff()中获取数据的方式.每次访问getStuff()时,都会获取一个新的ResultSet,但是不要关闭它.

这违反了Statement类的期望(见这里 – http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html):

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment’s current ResultSet object if an open one exists.

什么使事情更糟糕的是来自呼叫代码的rs.它也是从语句字段派生而不是关闭.

底线:您同时打开同一个Statement对象的几个ResultSet.

转载注明原文:获取java.sql.SQLException:ResultSet关闭后不允许操作 - 代码日志