gpt4 book ai didi

java - 如何使用 try-with-resources 检查 JDBC 连接是 Activity 的还是关闭的?

转载 作者:行者123 更新时间:2023-11-30 02:32:06 30 4
gpt4 key购买 nike

一旦try-with-resources语句执行完成后如何检查JDBC连接是 Activity 的还是关闭的?

代码:

try (Connection conn = ConnectionString.getConnection();
PreparedStatement psmt = conn.prepareStatement(SQL_Queries.GET_PUBLISHER_ID_QUERY);
ResultSet rs = psmt.executeQuery();)
{
psmt.setString(1, appId);
while (rs.next()) {
publisherId = rs.getString(Schema.PUBLISHER_PUBLISHID);
}

//System.out.println(conn != null ? "live" : "close");
}

最佳答案

这个想法是,使用 try-with-resource block ,您正在为连接创建一个内部范围。 try-with-resource 关闭连接并且 conn 对象范围结束,因此准备好进行垃圾回收。 Read more about scope here.

要检查这一点,请运行此代码

String url, username, pass;
url = "your-connection-url";
username = "db-username";
pass = "db-password";
Connection outerConnection = null;

try (Connection innerConnection = DriverManager.getConnection(url, username, pass);
PreparedStatement psmt = innerConnection.prepareStatement("SELECT 1");
ResultSet rs = psmt.executeQuery();)
{
while (rs.next()) {
System.out.println(rs.getString(1));
}

outerConnection = innerConnection;

// after the try catch, innerConnection won't exist anymore
// (the scope ends, the compiler compains if you access it outside the block!)
} catch (SQLException e)
{
e.printStackTrace();
}

if (outerConnection != null) {
try {
System.out.println("Is closed? " + outerConnection.isClosed());
}
catch (SQLException e) {
e.printStackTrace();
}
}
else {
System.out.println("Is null");
}

在控制台中您将得到

1
Is closed? true

关于java - 如何使用 try-with-resources 检查 JDBC 连接是 Activity 的还是关闭的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44044662/

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