JDBC批处理

package com.itheima.jdbc.demo4;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_pi_chu_li {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
    	
        
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection  conn = DriverManager.getConnection("jdbc:mysql://localhost/test?rewriteBatchedStatements=true", "root", "123456");
        //web_test3是要访问的数据库 root是数据库的用户 123456是数据库的密码
        // 默认情况下MySQL的批处理是没有开启的,需要在url后面拼接一个参数:rewriteBatchedStatements=true
        System.out.println("成功加载MYSQL驱动");
        PreparedStatement stmt = null;
       
		String sql="insert into user values (null,?)";
		
		stmt = conn.prepareStatement(sql);
		for(int i=0;i<10000;i++) {
			stmt.setString(1, "name"+i);
			
			stmt.addBatch();
			//添加批处理
			if(i%1000==0) {
				//添加批处理的数据是先把数据添加到内存中,为了避免数据太多,造成内存溢出,
				//所以在数据1000条的时候执行批处理,避免发生内存溢出
				stmt.executeBatch();
				stmt.clearBatch();
			}
		}
		conn.close();
		stmt.close();
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值