JDBC中的增删改操作

425 阅读1分钟
//**首先要写一个获取连接的方法和一个关闭资源的方法**
public class Test1 {
   public static Connection getConnection() throws Exception {
           InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
           
           //**此处的jdbc.properties为配置文件,内容将会在文章结尾展示**
           
           Properties properties = new Properties();
           properties.load(is);
           String user=properties.getProperty("user");
           String password=properties.getProperty("password");
           String url=properties.getProperty("url");
           String driverClass=properties.getProperty("driverClass");
           //**加载驱动**
           Class.forName(driverClass);
           //**获取连接**
           Connection conn = DriverManager.getConnection(url, user, password);
           return conn;
   }
   
   //关闭资源的方法
public static void closeResource(Connection conn, Statement ps){
   try {
       if(conn !=null)
           conn.close();
   } catch (Exception e) {
       e.printStackTrace();
   }
   try {
       if(ps!=null)
           ps.close();
   } catch (SQLException e) {
       e.printStackTrace();
   }
}
}

//此处为通用的增删改操作的方法
public void Operation(String sql,Object...args)throws Exception{
    //首先要获取数据库连接
    Connection conn=Test1.getConnection();
    //获取PreparedStatement实例
    PreparedStatement ps=conn.prepareStatement(sql);
    //通过for循环来填充占位符
    for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
    ps.execute()
    //关闭资源
    Test1.closeResource(conn,ps);
}

由于以上增删改操作的方法为抛出异常,可能会导致程序不健全,所以要对其进行修改

public void Operation(String sql,Object...args){
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            conn = Test1.getConnection();
            ps = conn.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            Test1.closeResource(conn,ps);
        }
    }

1.删除操作 (此处以customers表格为例)

@Test
public void test(){
        String sql="delete from customers where id=?";
        //填充你想要进行删除的数据的id号
        Operation(sql,3);
    }

2.添加操作

@Test
public void test(){
    String sql="
insert into customers(name,email,birth)values(?,?,?)
";
Operation(sql,"姓名","abc.abc",2002-1-1);
}

3.修改操作

@Test
    public void test(){
        String sql="
update customers set name=?,email=? where id=?
";
        Operation(sql,"姓名","abc.abc",3);
    }

jdbc.properties配置文件

user=用户名
password=密码
url=jdbc:mysql://localhost:3306/数据库名?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT&rewriteBatchedStatements=true
driverClass=com.mysql.cj.jdbc.Driver

customers表格数据

屏幕截图 2022-03-06 132325.png