gpt4 book ai didi

java - 我应该如何将 try-with-resources 与 JDBC 结合使用?

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

我有一种使用 JDBC 从数据库获取用户的方法:

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

我应该如何使用Java 7 try-with-resources改进这段代码?

我尝试过下面的代码,但它使用了许多try block ,并且并没有提高可读性太多。我应该以另一种方式使用 try-with-resources 吗?

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

最佳答案

我意识到这个问题很久以前就得到了回答,但想建议一种额外的方法来避免嵌套的 try-with-resources 双 block 。

public List<User> getUser(int userId) {
try (Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = createPreparedStatement(con, userId);
ResultSet rs = ps.executeQuery()) {

// process the resultset here, all resources will be cleaned up

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

关于java - 我应该如何将 try-with-resources 与 JDBC 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57512095/

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