JAVA JDBC 資料庫的一點記錄:事務
import java.sql.*;public class TestBatch {public static void main(String[] args) throws SQLException {Connection conn = null;Statement stmt = null;PreparedStatement pstmt = null;try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","ZHEN");conn.setAutoCommit(false);////事務1 transactionstmt = conn.createStatement(); //執行靜態 SQL 陳述式並返回它所產生結果的對象。 stmt.addBatch("INSERT INTO student VALUES(30,'ddd',12,'ii')");stmt.addBatch("INSERT INTO student VALUES(31,'ddd',12,'ii')");stmt.addBatch("INSERT INTO student VALUES(32,'ddd',12,'ii')");stmt.addBatch("INSERT INTO student VALUES(33,'ddd',12,'ii')");stmt.executeBatch();/////事務2pstmt = conn.prepareStatement("INSERT INTO student VALUES(?,?,?,?)");pstmt.setInt(1, 40);pstmt.setString(2,"qq");pstmt.setInt(3,5);pstmt.setString(4,"ww");pstmt.addBatch();pstmt.setInt(1, 41);pstmt.setString(2,"qq");pstmt.setInt(3,5);pstmt.setString(4,"ww");pstmt.addBatch();pstmt.executeBatch();///conn.commit(); //若事務1 和事務2必需要同時完成 或 同時不完成,不能存在只有其中一個被完成的情況,則要用transaction}catch (ClassNotFoundException e1) {e1.printStackTrace();}catch (SQLException e) {e.printStackTrace();conn.rollback(); //若交易處理失則,必需復原conn.setAutoCommit(true);}finally{stmt.close();pstmt.close();conn.close();}}}