Transaction transaction
/* Transaction transaction * JDBC turns on autocommit transactions by default, requires shutdown to manually control transactions * * Default MySQL storage engine for my ..., it does not support transactional processing, modified to INNODB engine * CREATE table name () en Gine=innodb default Charset=utf8; * * InnoDB engine turns off automatic transaction commit by default, modifies MySQL to commit transaction * Set autocommit=1; 1 for Auto Commit, 0 to turn off autocommit * Show variables like ' autocommit '; */ Public classTest01 { Public Static void Main(string[] args) {Connection conn =NULL; PreparedStatement pstmt =NULL; ResultSet rs =NULL; conn = Dbutil.getconnection ();Try{Conn.setautocommit (false);//Turn off autocommit transactions, manually control transactionsString sql ="INSERT into user values (null, ' eee ', ' 123 ')"; pstmt = conn.preparestatement (sql); Pstmt.executeupdate ();//Insert First userString sql2="INSERT into user values (' fff ', ' 123 ')"; Pstmt=conn.preparestatement (SQL2); Pstmt.executeupdate ();//Insert a second userConn.commit ();//Commit a transactionSystem. out. println ("Insert User success!" "); }Catch(SQLException e) {System. out. println ("Exception occurred, rollback TRANSACTION");Try{Conn.rollback ();//ROLLBACK TRANSACTION}Catch(SQLException E1) {E1.printstacktrace (); } }finally{Dbutil.closeall (RS, PSTMT, conn); } }}
Batch Processing
/ * * Batch processing * / Public classTest02 {Connection conn =NULL; Statement stmt =NULL; PreparedStatement pstmt=NULL; ResultSet rs =NULL; Public void test01() {Try{conn = dbutil.getconnection (); stmt = Conn.createstatement ();//Add batch-processing statementsStmt.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 ')");//Perform batch processing 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,?,?)");//Add batch-processing statementsPstmt.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 ();//Perform batch processing 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 =NewTest02 (); Test.test02 (); }}
Java Learning Note (54)-Transaction transaction and batching