gpt4 book ai didi

Java - 当我尝试关闭数据库资源时无法访问语句

转载 作者:行者123 更新时间:2023-12-01 18:29:30 25 4
gpt4 key购买 nike

每当我尝试关闭资源 rs.close() 或 stmt.close() 甚至 conn.close() 时,我都会收到一条错误消息,提示“无法访问语句”。奇怪的是,它在其他方法中也有效。也许我忘记了什么?

   public static boolean exists(int av) {

try {

Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
Statement stmt = conn.createStatement();
String query = "SELECT id FROM audiovisuals WHERE id='" + av + "' LIMIT 1";
ResultSet rs = stmt.executeQuery(query);

if(!rs.isBeforeFirst()) {
return false;
}
else {
return true;
}

rs.close();
stmt.close();
conn.close();

} catch (SQLException e) {

String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;

}

}

最佳答案

我在这里假设您收到了无法访问的语句,因为您将调用放在了 return 语句之后。您需要将关闭调用放在finally block 中。所以你的方法看起来像这样:

 Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {

conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
stmt = conn.createStatement();
String query = "SELECT id FROM audiovisuals WHERE id='" + av + "' LIMIT 1";
rs = stmt.executeQuery(query);

if(!rs.isBeforeFirst()) {
return false;
}
else {
return true;
}

} catch (SQLException e) {

String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;

} finally {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
}

关于Java - 当我尝试关闭数据库资源时无法访问语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24911657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com