JDBC的批量处理数据

在批量处理数据时,preparedStatement的处理效率要比statement效率高

preparedStatement的executeBatch发放批量提交效率更高


import java.sql.Statement;

import org.junit.Test;


public class JDBCTest {

/**
* 向oracle的customers数据表中插入10万条记录
* 1.PreparedStatement
* 批量插入用时Time: 6425
*
* 2.应用PreparedStament中的executeBatch发放批量提交
* 用时Time: 641
* */
@Test
public void TestBatchWithPreparedStatement(){
Connection connection = null;
PreparedStatement preparedStatement= null;
String sql = null;

try {
connection = JDBCTools.getConnection();
JDBCTools.beginTx(connection);

sql = "insert into customers values(?,?,?)";
preparedStatement = connection.prepareStatement(sql);
java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());

long begin = System.currentTimeMillis();
for(int i = 0;i < 100000 ; i++){
preparedStatement.setInt(1, i+1);
preparedStatement.setString(2, "name_"+(i+1));
preparedStatement.setDate(3, date);

//preparedStatement.executeUpdate();该条还不属于最厉害的批量添加方式

//通常我们用下边的方式进行批量添加操作
//"积攒"SQL
preparedStatement.addBatch();

//当"积攒"到一定程度,统一执行一次,并且清洗先前"积攒"的sql
if((i+1)% 400 ==0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
}

//若总条数不是批量数值的整数倍,则还需要再额外的执行一次
if(100000 % 400 != 0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}

long end = System.currentTimeMillis();

System.out.println("Time: " + (end - begin));

JDBCTools.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCTools.rollback(connection);
} finally{
JDBCTools.releaseDB(null, preparedStatement, connection);
}
}

/**
* 向oracle的customers数据表中插入10万条记录
* 1.statement
* 批量插入用时Time: 28244
* */
@Test
public void testBatchWithStatement() {
Connection connection = null;
Statement statement = null;
String sql = null;

try {
connection = JDBCTools.getConnection();
JDBCTools.beginTx(connection);

statement = connection.createStatement();

long begin = System.currentTimeMillis();
for(int i = 0;i < 100000 ; i++){
sql = "insert into customers values("+(i+1)+",'name_"+(i+1)+"','23-9月 -16')";
statement.executeUpdate(sql);
}
long end = System.currentTimeMillis();

System.out.println("Time: " + (end - begin));

JDBCTools.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCTools.rollback(connection);
} finally{
JDBCTools.releaseDB(null, statement, connection);
}
}

}

猜你喜欢

转载自wangyaweinihao.iteye.com/blog/2326293