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

后端 未结 5 2104
执笔经年
执笔经年 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:55

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

提交回复
热议问题