阅读背景:

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);
        }
    }
}
package com.demo.jdbc;

import com.demo.utils.J



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: