How should I use try-with-resources with JDBC?

后端 未结 5 2157
执笔经年
执笔经年 2020-11-22 09:06

I have a method for getting users from a database with JDBC:

public List getUser(int userId) {
    String sql = \"SELECT id, name FROM users WHER         


        
5条回答
  •  轮回少年
    2020-11-22 09:43

    There's no need for the outer try in your example, so you can at least go down from 3 to 2, and also you don't need closing ; at the end of the resource list. The advantage of using two try blocks is that all of your code is present up front so you don't have to refer to a separate method:

    public List getUser(int userId) {
        String sql = "SELECT id, username FROM users WHERE id = ?";
        List users = new ArrayList<>();
        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;
    }
    

提交回复
热议问题