博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Batch批量添加数据
阅读量:4469 次
发布时间:2019-06-08

本文共 2114 字,大约阅读时间需要 7 分钟。

package com.atguigu.jdbc;

import java.sql.Connection;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.Statement;

import org.junit.Test;

public class JDBCTest {

@Test
public void testBatch(){
Connection connection=null;
PreparedStatement preparedStatement=null;
try{
connection=JDBCTools.getConnection();
JDBCTools.beginTx(connection);
String sql="insert into customers values(?,?,?)";
preparedStatement=connection.prepareStatement(sql);
long beginTime=System.currentTimeMillis();
for(int i=0;i<100000;i++){
preparedStatement.setInt(1,i+100001);
preparedStatement.setString(2, "");
preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
//preparedStatement.executeUpdate();
//积攒SQL
preparedStatement.addBatch();
//当积攒到一定程度,就统一的执行一次,并且清空先前积攒的SQL
if((i+1)%300==0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
}
//若总条数不是批量数值的整数倍,则还需要再额外执行一次
if((100000%300)!=0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
long stopTime=System.currentTimeMillis();
JDBCTools.commit(connection);
System.out.println(beginTime-stopTime);
}catch(Exception e){
e.printStackTrace();
JDBCTools.rollback(connection);
}finally{
JDBCTools.release(null, preparedStatement, connection);
}
}
@Test
public void testBatchWithPreparedStatement(){
Connection connection=null;
PreparedStatement preparedStatement=null;
try{
connection=JDBCTools.getConnection();
JDBCTools.beginTx(connection);
String sql="insert into customers values(?,?,?)";
preparedStatement=connection.prepareStatement(sql);
long beginTime=System.currentTimeMillis();
for(int i=0;i<100000;i++){
preparedStatement.setInt(1,i+100001);
preparedStatement.setString(2, "");
preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
preparedStatement.executeUpdate();
}
long stopTime=System.currentTimeMillis();
JDBCTools.commit(connection);
System.out.println(beginTime-stopTime);
}catch(Exception e){
e.printStackTrace();
JDBCTools.rollback(connection);
}finally{
JDBCTools.release(null, preparedStatement, connection);
}
}

}

转载于:https://www.cnblogs.com/xiaona19841010/p/5204359.html

你可能感兴趣的文章
HBase表预分区
查看>>
NSBundle,UIImage,UIButton的使用
查看>>
GridView 中Item项居中显示
查看>>
UML类图五种关系与代码的对应关系
查看>>
如何理解作用域
查看>>
从无到满意offer,你需要知道的那些事
查看>>
P1516 青蛙的约会 洛谷
查看>>
SDOI2011 染色
查看>>
JQuery EasyUI combobox动态添加option
查看>>
面向连接的TCP概述
查看>>
前端快捷方式 [记录]
查看>>
亲测可用,解决端口被占用的指令!!
查看>>
MySQL--视图、触发器、事务、存储过程、内置函数、流程控制、索引
查看>>
Django--数据库查询操作
查看>>
自定义配置文件的使用
查看>>
js-20170609-运算符
查看>>
算法笔记_065:分治法求逆序对(Java)
查看>>
MSP430FLASH小结
查看>>
STM32 ADC转换时间
查看>>
结合实际业务场景聊一聊MVP模式的应用
查看>>