“使用PreparedStatement实现修改操作”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
(建立内容为“https://www.bilibili.com/video/BV1eJ411c7rf?p=15”的新页面)
 
 
第1行: 第1行:
https://www.bilibili.com/video/BV1eJ411c7rf?p=15
+
https://www.bilibili.com/video/BV1eJ411c7rf?p=15<syntaxhighlight lang="java">
 +
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);
 +
        }
 +
 
 +
 
 +
    }
 +
……
 +
</syntaxhighlight>https://github.com/jihch/jdbc/blob/main/src/main/java/io/github/jihch/preparedstatement/crud/PreparedStatementUpdateTest.java

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