批量添加数据简介
在JDBC中通过PreparedStatement的对象的addBatch()和executeBatch()方法进行数据的批量插入。
- addBatch()把若干SQL语句装载到一起,然后一次性传送到数据库执行,即是批量处理sql数据的。
- executeBatch()会将装载到一起的SQL语句执行。
注意:
MySql默认情况下是不开启批处理的。
数据库驱动从5.1.13开始添加了一个对rewriteBatchStatement的参数的处理,该参数能够让MySql开启批处理。在url中添加该参数:rewriteBatchedStatements=true
mysql的url参数
useUnicode | [true | false] | 是否使用编码集,需配合 characterEncoding 参数使用。 |
---|---|---|
characterEncoding | [utf-8 | gbk | …] | 编码类型。 |
useSSL | [true | false] | 是否使用SSL协议。 |
rewriteBatchedStatements | [true | false] | 可以重写向数据库提交的SQL语句。 |
若有多个参数可&连接
如:?useSSL=false&charecterEncoding=true
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
* 向mysql数据库批量添加数据
*/
public class AddBatchTest {
/**
* 批量添加数据方式一(数据量小)
*/
public void addBatch_1(){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement("insert into users values (default ,?,?)");
//参数绑定
for(int i=0;i<1000;i++){
preparedStatement.setString(1,"laogeng"+i);
preparedStatement.setInt(2,20);
//缓存sql
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.clossResource(preparedStatement,connection);
}
}
/**
* 批量添加数据方式二(数据量大)
*/
public void addBatch_2(){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement("insert into users values (default ,?,?)");
//参数绑定
for(int i=0;i<1000;i++){
preparedStatement.setString(1,"laogeng"+i);
preparedStatement.setInt(2,20);
//缓存sql
preparedStatement.addBatch();
if(i%500==0){
preparedStatement.executeBatch();
//清缓存
preparedStatement.clearBatch();
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.clossResource(preparedStatement,connection);
}
}
public static void main(String[] args) {
AddBatchTest addBatchTest = new AddBatchTest();
addBatchTest.addBatch_2();
}
}