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

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

    What about creating an additional wrapper class?

    package com.naveen.research.sql;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public abstract class PreparedStatementWrapper implements AutoCloseable {
    
        protected PreparedStatement stat;
    
        public PreparedStatementWrapper(Connection con, String query, Object ... params) throws SQLException {
            this.stat = con.prepareStatement(query);
            this.prepareStatement(params);
        }
    
        protected abstract void prepareStatement(Object ... params) throws SQLException;
    
        public ResultSet executeQuery() throws SQLException {
            return this.stat.executeQuery();
        }
    
        public int executeUpdate() throws SQLException {
            return this.stat.executeUpdate();
        }
    
        @Override
        public void close() {
            try {
                this.stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    


    Then in the calling class you can implement prepareStatement method as:

    try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
        PreparedStatementWrapper stat = new PreparedStatementWrapper(con, query,
                    new Object[] { 123L, "TEST" }) {
                @Override
                protected void prepareStatement(Object... params) throws SQLException {
                    stat.setLong(1, Long.class.cast(params[0]));
                    stat.setString(2, String.valueOf(params[1]));
                }
            };
            ResultSet rs = stat.executeQuery();) {
        while (rs.next())
            System.out.println(String.format("%s, %s", rs.getString(2), rs.getString(1)));
    } catch (SQLException e) {
        e.printStackTrace();
    }
    

提交回复
热议问题