使用PreparedStatement实现通用的增删改操作

来自姬鸿昌的知识库
Jihongchang讨论 | 贡献2022年12月20日 (二) 20:05的版本
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1eJ411c7rf?p=16

CREATE TABLE `order` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `order_name` varchar(45) DEFAULT NULL,
  `order_date` date DEFAULT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
INSERT INTO `jdbc_test`.`order` (`order_name`, `order_date`) VALUES('AA', '2010-03-04');
import io.github.jihch.util.JDBCUtils;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;

/**
 * 使用 PreparedStatement 来替换 Statement,实现对数据表的增删改查操作
 * 增删改;查
 */
public class PreparedStatementUpdateTest {

    @Test
    public void testCommonUpdate() {
//        String sql = "delete from customers where id = ?";
//        update(sql, 1);

        String sql = "update `order` set order_name = ? where order_id = ?";
        update(sql, "DD", 1);

    }

    //通用的增删改查操作
    public void update(String sql, Object ...args) {//sql 中占位符的个数与可变形参的长度相同

        Connection conn = null;
        PreparedStatement ps = null;

        try {
            //1.获取数据库的连接
            conn = JDBCUtils.getConnection();

            //2.预编译sql语句,返回PreparedStatement的实例
            ps = conn.prepareStatement(sql);

            //3.填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            //4.执行
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps);
        }

    }

https://github.com/jihch/jdbc/blob/main/src/main/java/io/github/jihch/preparedstatement/crud/PreparedStatementUpdateTest.java