语句中的 try-with-resources 是否会关闭连接?
Does try-with-resources on a statement close the connection?
在这段代码中,连接会被关闭吗?
Connection con = DriverManager.getConnection(dbUrl, user, pass);
try (Statement st = con.createStatement()) {
ResultSet rs = st.executeQuery(query);
}
我的代码中出现意外关闭连接的情况,我想确定不是这个原因。
不,在语句上调用 close
不会关闭连接。这将阻止我们在已经打开的连接上创建下一条语句,这意味着我们必须为每个语句创建新的连接(这可能是昂贵的操作)。
你可以很容易地测试它。在上一个语句关闭后尝试创建另一个语句。
Connection con = DriverManager.getConnection(dbUrl,user,pass);
try (Statement st = con.createStatement()) {
ResultSet rs = st.executeQuery(sqlQuery1);
simplePrint(rs);
} catch (SQLException e) {
e.printStackTrace();
}//here `st` will be closed automatically by try-with-resources
try (Statement st = con.createStatement()) {//lets try to create next statement
ResultSet rs = st.executeQuery(sqlQuery2);
simplePrint(rs);
} catch (SQLException e) {
e.printStackTrace();
}
simplePrint
方法可能如下所示:
public static void simplePrint(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.print(rs.getObject(i)+"\t");
}
System.out.println();
}
}
在这段代码中,连接会被关闭吗?
Connection con = DriverManager.getConnection(dbUrl, user, pass);
try (Statement st = con.createStatement()) {
ResultSet rs = st.executeQuery(query);
}
我的代码中出现意外关闭连接的情况,我想确定不是这个原因。
不,在语句上调用 close
不会关闭连接。这将阻止我们在已经打开的连接上创建下一条语句,这意味着我们必须为每个语句创建新的连接(这可能是昂贵的操作)。
你可以很容易地测试它。在上一个语句关闭后尝试创建另一个语句。
Connection con = DriverManager.getConnection(dbUrl,user,pass);
try (Statement st = con.createStatement()) {
ResultSet rs = st.executeQuery(sqlQuery1);
simplePrint(rs);
} catch (SQLException e) {
e.printStackTrace();
}//here `st` will be closed automatically by try-with-resources
try (Statement st = con.createStatement()) {//lets try to create next statement
ResultSet rs = st.executeQuery(sqlQuery2);
simplePrint(rs);
} catch (SQLException e) {
e.printStackTrace();
}
simplePrint
方法可能如下所示:
public static void simplePrint(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.print(rs.getObject(i)+"\t");
}
System.out.println();
}
}