Java中,使用JDBC进行数据库操作时,可以利用try-with-resources语句来自动释放资源,包括数据库连接、语句和结果集。try-with-resources语句能够在程序执行完毕或者发生异常时自动关闭资源,无需手动编写关闭资源的代码,这样可以有效地避免资源泄漏和简化代码。

1、一般写法jdbc使用的try catch代码

public List<User> getUser(int userId) {
String sql = "SELECT id, name FROM users WHERE id = ?";
List<User> users = new ArrayList<User>();
try {
Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, userId);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
users.add(new User(rs.getInt("id"), rs.getString("name")));
}
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}

2、Jdbc使用try-with-resources自动资源释放代码

public List<User> getUser(int userId) {
    try (Connection con = DriverManager.getConnection(myConnectionURL);
         PreparedStatement ps = createPreparedStatement(con, userId); 
         ResultSet rs = ps.executeQuery()) {
         //...
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
private PreparedStatement createPreparedStatement(Connection con, int userId) throws SQLException {
    String sql = "SELECT id, username FROM users WHERE id = ?";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setInt(1, userId);
    return ps;
}

推荐文档