我应该如何在JDBC中使用try-with-resources? [英] How should I use try-with-resources with JDBC?
本文介绍了我应该如何在JDBC中使用try-with-resources?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一种方法可以使用JDBC从数据库中获取用户:
I have a method for getting users from a database with 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 试用资源 来改进此代码?
How should I use Java 7 try-with-resources to improve this code?
我尝试使用下面的代码,但它使用了许多尝试
,并没有改善可读性许多。我应该以另一种方式使用 try-with-resources
吗?
I have tried with the code below, but it uses many try
, and doesn't improve the readability much. Should I use try-with-resources
in another way?
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双重阻止。
I realize this was long ago answered but want to suggest an additional approach that avoids the nested try-with-resources double 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;
}
这篇关于我应该如何在JDBC中使用try-with-resources?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文