Encapsulation of adding, deleting and modifying database by JDBC

private static final String CLASS_FORNAME = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://127.0.0.1:3306/test";
private static final String USER = "ROOT";
private static final String PASSWORD = "123456";

static{
    try {
        Class.forName(CLASS_FORNAME);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

public static Connection getConn(){
    try {
        return DriverManager.getConnection(URL,USER,PASSWORD);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}

public static void close(Connection conn, Statement ps, ResultSet rs){
    try {
        conn.close();
        ps.close();
        rs.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
public static boolean update(String sql,Object...obj){
    Connection conn = getConn();
    PreparedStatement ps = null;
    try{
        ps =conn.prepareStatement(sql);
        if (Objects.nonNull(obj)) {
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i+1,obj[i]);
            }
        }
        int b = ps.executeUpdate();
        return b >0;
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        close(conn,ps,null);
    }
    return false;
}

Thinking: the JDBC database operation step cannot modify data set as a constant, then the access to database objects and close the resources as method, will be updated as method, namely the deletion operation, the operation of SQL to update for us, then the array as the incoming conditions, first of all determine whether array is empty, if the data is not empty


Read More: