Javaweb学习笔记之JDBC(五):批处理执行 sql 语句

package com.demo.jdbc;

import com.demo.utils.JdbcUtils2;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

/**
 * 批处理执行 sql 语句
 *  addBatch(String sql)     添加批处理
 *  clearBatch()             清空批处理
 *  executeBatch()           执行批处理
 */
public class JdbcDemo5 {
    @Test
    public void test1(){
        Connection conn = null;
        PreparedStatement pstmt = null;

        // 模拟批量数据
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            User user = new User("Jack" + i, "123" + i);
            list.add(user);
        }

        try{
            // 1、获取数据库连接对象
            conn = JdbcUtils2.getConnection();
            // 2、准备预编译 sql 语句
            String sql = "insert into users(username, password) values(?, ?)";
            // 3、预编译 sql 语句,创建 pstmt 对象
            pstmt = conn.prepareStatement(sql);

            for (int i = 0; i < list.size(); i++) {
                User user = list.get(i);
                // 4、设置参数
                pstmt.setString(1, user.getUsername());
                pstmt.setString(2, user.getPassword());

                // 5、添加批处理
                pstmt.addBatch();

                // 6、每 5条 执行一次批处理
                if (i % 5 == 0){
                    pstmt.executeBatch();   // 执行批处理
                    pstmt.clearBatch();     // 清空批处理
                    System.out.println("执行了批处理!i:" + i);
                }
            }

            pstmt.executeBatch();   // 执行批处理
            pstmt.clearBatch();     // 清空批处理
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils2.close(conn, pstmt, null);
        }
    }
}

其中 JdbcUtils2.java 工具类为:https://blog.csdn.net/qq_29331365/article/details/95166514

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值