如何检查JDBC连接是实时还是关闭使用try-with-resources?

时间:2017-05-18 10:02:51

标签: java jdbc

在如何检查JDBC连接是实时还是关闭之后,一旦try-with-resources语句执行完成?

代码:

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");
}

2 个答案:

答案 0 :(得分:2)

我们的想法是使用try-with-resource块,为连接创建内部范围。 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

答案 1 :(得分:0)

首先,Connection对象范围仅限于try块,它在它之外是不可见的。

其次,你自己说,try-with-resources语句中的所有资源都必须全部实现AutoCloseable,在语句结束时关闭。因此,即使您的Connection可见,它也会被关闭。