1 PackageCom.ayang.jdbc;2 3 ImportJava.sql.*;4 /**5 * Transaction composition, casually write a sentence insenrt, an execution executeupdate (), it is automatically submitted. 6 * The example below has three UPDATE statements, assuming that the first is the UpdateA account on the end of the money, automatic submission, this time error, B account on the money did not update, this time there will be inconsistent data issues. 7 * The solution is simple, put it in a transtraction, either two is done at the same time, or it is not done. 8 * Any DML statement is automatically committed because there is a property in the entire database connection: Autocommit (), and default value True, which is automatically committed. To put some statements in a transaction,9 * Put autocommit (false), set to False, commit manually: Last execution Conn.commit (), and then restore Autocommit () to True.Ten * If catch to any sqlexception, first make conn.rollback (); then Conn.setautocommit (true); ensure foolproof. One */ A - - Public classtesttransaction { the - Public Static voidMain (string[] args) { -Connection conn =NULL; -Statement stmt =NULL; + Try { -Class.forName ("Oracle.jdbc.driver.OracleDriver"); +conn = Drivermanager.getconnection ("Jdbc:oracle:thin:@127.0.0.1:1521:orcl", "Scott", "Root"); A atConn.setautocommit (false); -stmt =conn.createstatement (); -Stmt.addbatch ("INSERT into DEPT2 values", ' CPU ', ' Xuchang ')); -Stmt.addbatch ("INSERT into dept2 values (", ' CPU ', ' Xuchang ') "); -Stmt.addbatch ("INSERT into DEPT2 values (+, ' CPU ', ' Xuchang ')"); - Stmt.executebatch (); in conn.commit (); -Conn.setautocommit (true); to + -}Catch(ClassNotFoundException e) { the e.printstacktrace (); *}Catch(SQLException e) { $ e.printstacktrace ();Panax Notoginseng - Try { the if(Conn! =NULL){ +Conn.rollback ();//Rollback If there is an exception. AConn.setautocommit (true); the + } -}Catch(SQLException E1) { $ e1.printstacktrace (); $}finally{ - Try{ - if(conn!=NULL){ the conn.close (); -}if(stmt!=NULL){Wuyi stmt.close (); the } -}Catch(SQLException E1) { Wu e1.printstacktrace (); - } About } $ } - - - A } + the}
Auto-Submit effect comparison, can insert top two records (the third SQL statement is missing Into ) The third SQL does not execute.
Conn.setautocommit (FALSE);
stmt = Conn.createstatement ();
Stmt.addbatch ("INSERT into dept2 values (' CPU ', ' Xuchang ')");
Stmt.addbatch ("INSERT into DEPT2 values (+, ' CPU ', ' Xuchang ')");
Stmt.addbatch ("Insert dept2 values (+, ' CPU ', ' Xuchang ')");
Stmt.executebatch ();
Conn.commit ();
Conn.setautocommit (TRUE);
JDBC Processing Transaction