JAVA學習筆記(五十四)- 事務Transaction與批處理
阿新 • • 發佈:2019-02-14
/*
* 批處理
*/
public class Test02 {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt=null;
ResultSet rs = null;
public void test01() {
try {
conn = DBUtil.getConnection();
stmt = conn.createStatement();
// 新增批處理語句
stmt.addBatch("insert into user values (null,'s001','123')" );
stmt.addBatch("insert into user values (null,'s002','123')");
stmt.addBatch("insert into user values (null,'s003','123')");
// 執行批處理
int[] nums = stmt.executeBatch();
System.out.println(Arrays.toString(nums));
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.closeAll(rs, stmt, conn);
}
}
public void test02() {
try {
conn = DBUtil.getConnection();
conn.setAutoCommit(false);
pstmt=conn.prepareStatement("insert into user values (null,?,?)");
// 新增批處理語句
pstmt.setObject(1 , "t001");
pstmt.setObject(2, "123");
pstmt.addBatch();
pstmt.setObject(1, "t002");
pstmt.setObject(2, "123");
pstmt.addBatch();
pstmt.setObject(1, "t003");
pstmt.setObject(2, "123");
pstmt.addBatch();
// 執行批處理
int[] nums=pstmt.executeBatch();
System.out.println(Arrays.toString(nums));
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
DBUtil.closeAll(rs, stmt, conn);
}
}
public static void main(String[] args) {
Test02 test = new Test02();
test.test02();
}
}