我的代码有问题: 错误:ORA-01000:超出最大打开光标。从多个线程调用此代码。 问:oracle游标是否与JDBC游标(结果集)不同?
public static void viewTable(Connection con, String TBName)
throws SQLException {
Statement stmt = null;
String query = "select *from " + TBName;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String studentName = rs.getString("STD_NAME");
System.out.println(studentName + "\t");
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { stmt.close(); }
}
}
答案 0 :(得分:2)
您应该始终关闭ResultSet和Statement。正如您所说,您的代码可以被许多线程访问,因此很多Resultset将是开放的,永远不会 闭合。
将ResultSet变量放在try catch块之外,并在Statement结束旁边的finally中关闭它。
答案 1 :(得分:2)
使用try-with-resources确保语句和结果集都已关闭。
String query = "select STD_NAME from " + TBName;
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
String studentName = rs.getString("STD_NAME");
System.out.println(studentName + "\t");
}
} // Closes rs and stmt even with exceptions.