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

后端 未结 5 2105
执笔经年
执笔经年 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条回答
  •  旧时难觅i
    2020-11-22 09:46

    Here is a concise way using lambdas and JDK 8 Supplier to fit everything in the outer try:

    try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
        PreparedStatement stmt = ((Supplier)() -> {
        try {
            PreparedStatement s = con.prepareStatement("SELECT userid, name, features FROM users WHERE userid = ?");
            s.setInt(1, userid);
            return s;
        } catch (SQLException e) { throw new RuntimeException(e); }
        }).get();
        ResultSet resultSet = stmt.executeQuery()) {
    }
    

提交回复
热议问题