JDBC的批量处理数据

时间:2021-10-15 19:16:32

主要用到的方法有:

preparedStatement.executeBatch();//积攒的数据执行
preparedStatement.clearBatch();//积攒的清除掉

preparedStatement.addBatch();//这儿并不马上执行,积攒到一定数量之后,刷新执行
-----------------------------------------------------------------------------------------------

Test12 t=new Test12();

/*
* 批量处理数据JDBC语句,提高处理速度
* */
//插入数据
@Test
public void testBase() throws Exception{
Connection connection=null;
PreparedStatement preparedStatement=null;
String sql=null;
try {
connection=t.getConnection();
//开始事物取消默认提交
setAutoCommit(connection);
sql="insert into customer where values(?,?,?,?)";
preparedStatement=connection.prepareStatement(sql);
Date date=new Date(new java.util.Date().getTime());

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

//preparedStatement.executeQuery();
//这儿并不马上执行,积攒到一定数量之后,刷新执行
preparedStatement.addBatch();
if((i+1)%300==0){
preparedStatement.executeBatch();//积攒的数据执行
preparedStatement.clearBatch();//积攒的清楚掉
}
}
//最后不是300的整数,再执行一次
if(1000000%300!=0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
long end=System.currentTimeMillis();
System.out.println(end-began);
//都成的话,提交事物
commit(connection);
} catch (Exception e) {

}finally {//回滚事物
rollbank(connection);
t.close(connection, preparedStatement, null);
}

}
//开始事物:取消默认提交
public void setAutoCommit(Connection connection){
if(connection!=null){
try {
connection.setAutoCommit(false);
} catch (SQLException e) {

e.printStackTrace();
}
}
}
//都成功提交事物
public void commit(Connection connection){
if(connection!=null){
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}

}
//回滚事物
public void rollbank(Connection connection){
if(connection!=null){
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public void TestSetTransactionTsolation(){
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
connection=t.getConnection();
//设置不是自动提交
connection.setAutoCommit(false);

String sql1="update test set grade= grade+100 where flow_id=3";
t1.update(connection, sql1);

//都成功提交事物
connection.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {

}
}