package day01;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class Batch {
/*
* 批處理的三種方式
*
* 預編譯是用于執行DML語句(對資料批量的增删改)
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// exeBatchSql();
// exeBatchPrepareSql();
exeBatchmixedSql();
}
* 沒有預編譯的批處理(靜态SQL)
public static void exeBatchStaticSql() throws Exception {
Connection connection = BaseSource.getConnection();
Statement statement = connection.createStatement();
for (int i = 0; i << font=""> 100; i++) {
//批量的添加資料,緩存起來
statement.addBatch("insert into emp values('a'," + i + ",'b','c')");
if (i % 50 == 0) {// 如果批處理的資料太多,可以控制批處理的數量,但要記得clearBatch()
statement.executeBatch();
statement.clearBatch();
}
}
statement.executeBatch();//緩存的SQL一次發給資料庫
connection.close();
* 預編譯的批處理
public static void exeBatchPrepareSql() throws Exception {
PreparedStatement prepareStatement = connection
.prepareStatement("insert into emp values(?,?,?,?)");
for (int i = 100; i << font=""> 200; i++) {
prepareStatement.setString(1, "a");
prepareStatement.setInt(2, i);
prepareStatement.setString(3, "b");
prepareStatement.setString(4, "c");
prepareStatement.addBatch();// 設定完一條完整的資料後addBatch()
for (int i = 200; i << font=""> 300; i++) {
prepareStatement.addBatch();
prepareStatement.executeBatch();
* 預編譯和靜态SQL 混合使用
public static void exeBatchmixedSql() throws Exception {
prepareStatement.setString(1, "a");
prepareStatement.setInt(2, 400);
prepareStatement.setString(3, "b");
prepareStatement.setString(4, "c");
prepareStatement.addBatch();//預編譯的批處理
prepareStatement.addBatch("insert into emp values('a'," + 401 + ",'b','c')");//靜态的預編譯
}