JDBC的批量處理數據


主要用到的方法有:

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 {

}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM