1. 程式人生 > >向資料庫批量處理事件

向資料庫批量處理事件

Connection conn;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://88.88.88.88:3306/zmm?useUnicode=true&characterEncoding=UTF-8", "root", "root");
conn.setAutoCommit(false);
// 儲存當前自動提交模式
boolean autoCommit = conn.getAutoCommit();
// 關閉自動提交
conn.setAutoCommit(false);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

 for (String key : map.keySet()) {

//編輯

stmt.addBatch("update zmm set id= '" + zmm+ "',zmm = '" + zmm+ "',status = 0 where id ='"+id+"'");

//插入

//stmt.addBatch("insert into zmm set id = '"+id+"', create_date = '"+sdf.format(date)+"', cut_off_date = null, zmm= '" + zmm+ "',status = 0");

//list.size()或者map.size()都可以點size方法

if (i % 1000 == 0 || i == list.size()) {
try {
stmt.executeBatch();
stmt.clearBatch();
conn.commit();
} catch (Exception e) {
conn.close();
e.printStackTrace();
}

i = i + 1;

}

//關閉事件

conn.close();