有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java结果集提前关闭

我正在从一个运行的MYSQL数据库编译一个页面变量列表(其中包含一个书籍列表)。在while(rs.next())循环中尝试第二次迭代时,我收到一个SQL异常,表示结果集已经关闭。我看不出这个代码关闭了rs对象

try {
    stmt = con.createStatement();
    ResultSet rs =
            stmt.executeQuery("SELECT pageURL," +
                    "pageName FROM pages GROUP BY pageName;");
    ResultSet rs2;
    while(rs.next()) { // Where the error occurs on the second pass
        Page tempP = new Page(rs.getString(1),rs.getString(2));
        rs2 = stmt.executeQuery("SELECT `books`.`itemID`,cost," +
                "title,author,shortD,longD FROM " +
                "books INNER JOIN pages ON " +
                "books.itemID=pages.itemID WHERE " +
                "pageName='" + rs.getString(2) + "';");
        while(rs2.next()) {
            tempP.addBook(new Book(rs2.getInt(1),
                    rs2.getFloat(2),rs2.getString(3),
                    rs2.getString(4),rs2.getString(5),
                    rs2.getString(6)));
        }
        pages.addPage(tempP);
    }
} catch(SQLException e) {
    System.err.print("SQLException: ");
    System.err.println(e.getMessage());
}

以下是pages表的内容:

|pageName  |pageURL    |itemID|
-------------------------------
|Tech Books|./techbooks|1     |
-------------------------------
|Tech Books|./techbooks|2     |
-------------------------------
|Kids Books|./kidsbooks|3     |
-------------------------------
|Kids Books|./kidsbooks|4     |
-------------------------------
|Kids Books|./kidsbooks|5     |
-------------------------------

编辑:

好吧,当我再次使用该语句时,结果集似乎变得无效。有人有什么建议来补救这种情况吗


共 (1) 个答案

  1. # 1 楼答案

    引用javadocs for语句:

    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.

    创建两个语句,或者更好地使用带绑定变量的PreparedStatements