1. 批處理
- 批處理只針對更新(增,刪,改)語句.
- MySql 的批處理默認是關閉的, 需要在 url 中配置參數:
jdbc:mysal://localhost:3306/mydb1?rewriteBatchedStatements=true
2. PreparedStatement 批處理
- PreparedStatement 對象內部有集合.
- 使用循環瘋狂的向 pstmt 中添加 sql 參數, 使用一組參數與模板就可以匹配出
一條 sql 語句. - 調用它的執行批方法, 完成向數據庫發送.
// PreparedStatement 批處理
public class Demo{
public void fun() throws SQLException {
// 獲取 PreparedStatement 對象
Connection con = JdbcUtils.getConnection();
String sql = "INSERT INTO stu VALUES(?,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql);
// 使用循環瘋狂添加參數
for(int i = 0; i< 10000; i++){
pstmt.setInt(1,i+1); // 學號
pstmt.setString(2, "stu_"+i); // 姓名
pstmt.setInt(3,i); // 年齡
pstmt.setString(4, i%2==0?"male":"female"); //性別
// 添加批, 這一組參數就保存到集合中.
pstmt.addBatch();
}
// 執行批方法, 向數據庫發送 sql 語句
pstmt.executeBatch();
}
}
參考資料: