JDBC的批量處理資料

來源:互聯網
上載者:User

標籤:

主要用到的方法有:

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 {

}
}

JDBC的批量處理資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.