使用PreparedStatement实现修改操作

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

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

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 {

    /**
     * 修改 customers 表的一条记录
     */
    @Test
    public void testUpdate() {
        Connection conn = null;
        PreparedStatement ps = null;

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

            //2.预编译 sql 语句,返回 PreparedStatement 的实例
            String sql = "update customers set name = ? where id = ?";
            ps = conn.prepareStatement(sql);

            //3.填充占位符
            ps.setObject(1, "李靖");
            ps.setObject(2, 1);

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

            //5.资源的关闭
            JDBCUtils.closeResource(conn, ps);
        }


    }
……

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