1 import java.sql.*; 2 public class TestTransaction { 3 4 5 public static void main(String[] args) { 6 7 Connection conn = null; 8 Statement stmt = null; 9 10 try { 11 Class.forName("oracle.jdbc.driver.OracleDriver"); 12 conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:SXT", "scott", "tiger"); 13 //先关闭默认打开的AutoCommit 14 conn.setAutoCommit(false); 15 stmt = conn.createStatement();
//关闭实现操作 16 stmt.addBatch("insert into dept2 values (51, '500', 'haha')"); 17 stmt.addBatch("insert into dept2 values (52, '500', 'haha')"); 18 stmt.addBatch("insert into dept2 values (53, '500', 'haha')"); 19 stmt.executeBatch(); 20 conn.commit();
//执行完后要恢复为true
21 conn.setAutoCommit(true); 22 } catch (ClassNotFoundException e) { 23 e.printStackTrace(); 24 } catch(SQLException e) { 25 26 e.printStackTrace(); 27 28 try { 29 if(conn != null) 30 { 31 conn.rollback(); 32 conn.setAutoCommit(true); 33 } 34 } catch (SQLException e1) { 35 e1.printStackTrace(); 36 } 37 }finally { 38 try { 39 if(stmt != null) 40 stmt.close(); 41 if(conn != null) 42 conn.close(); 43 } catch (SQLException e) { 44 e.printStackTrace(); 45 } 46 } 47 48 49 } 50 51 }