我正在从正在运行的 MYSQL 数据库编译页面变量列表(其中包含书籍列表)。当尝试在 while(rs.next()) 循环中进行第二次迭代时,我收到一个 SQL 异常,指出 ResultSet 已关闭。我没有看到这段代码关闭了 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());
}
以下是页面表的内容:
|pageName |pageURL |itemID|
-------------------------------
|Tech Books|./techbooks|1 |
-------------------------------
|Tech Books|./techbooks|2 |
-------------------------------
|Kids Books|./kidsbooks|3 |
-------------------------------
|Kids Books|./kidsbooks|4 |
-------------------------------
|Kids Books|./kidsbooks|5 |
-------------------------------
编辑:
好吧,看来当我再次使用该Statement时,ResultSet就失效了。有没有人有任何建议来解决这种情况?
最佳答案
引用声明的javadoc:
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.
创建两个语句,或者更好的是使用带有绑定(bind)变量的PreparedStatements。
关于java - 结果集过早关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1760099/