JDBC封装增删改操作-LMLPHPJDBC封装增删改操作-LMLPHP

package com.utils;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * @author hrui
 * @date 2023/10/13 13:49
 */
public class DBUtils {
    private static ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
    private static String driver=bundle.getString("jdbc.driver");
    private static String url=bundle.getString("jdbc.url");
    private static String username=bundle.getString("jdbc.username");
    private static String password=bundle.getString("jdbc.password");

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

    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }
    
    //获取连接也可以合并掉
    public static int update(String sql,Object...args){
        Connection conn =null;
        PreparedStatement ps=null;
        int count=0;
        try {
            conn = DBUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1, args[i]);
            }
            //ps.execute();这个方法可以用于增删改查操作,如果返回true则是有ResultSet结果集
            count = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils.closed(conn,ps,null);
        }

        return count;
    }


    public static void closed(Connection conn, Statement st, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

测试

public class Test {
    public static void main(String[] args) throws SQLException {
//        String sql="insert into customers(id,name,email,birth,photo) values(null,?,?,?,null)";
//        DBUtils.update(sql,"小明","xiaoming@email.com","2022-02-02");
        String sql="update customers set name=? where id=?";
        int count = DBUtils.update(sql,"小王", 19);
        System.out.println(count);
    }
}
10-14 08:07