package jdbc02;import java.sql.connection;import java.sql.preparedstatement;import java.sql.sqlexception;import org.junit.test;import jdbc02.*;p Ublic class transactiontest {/** * Tom Send jerry 500 RMB * * about transaction: * 1. if more than one operation, Each operation uses its own separate connection, and the transaction cannot be guaranteed. * 2. concrete steps * 1) Start transaction before transaction operation: Cancel connection default commit behavior * 2) If the operation of the transaction succeeds, commit the transaction, * 3) roll back the transaction */@Testpublic void testtransaction () {connection Connection = null;try {connection = jdbctools.getconnection2 ();//Start transaction: Cancels the default commit connection.setautocommit (FALSE); System.out.println (Connection.getautocommit ()); string sql1 = "update users set balance = balance-500 where id = ? "; string sql2 = "update users set balance = balance+500 where id = ? "; Update (ConNECTION,&NBSP;SQL1,&NBSP;2); Int i = 10 / 0 ; update (CONNECTION,&NBSP;SQL2, &NBSP;1);//COMMIT Transaction Connection.commit ();} catch (exception e) {// TODO Auto-generated catch Blocke.printstacktrace ();//ROLLBACK TRANSACTION try {connection.rollback ();;} catch (SQLEXCEPTION&NBSP;E1) {// TODO Auto-generated catch Blocke1.printstacktrace ();}} Finally{jdbctools.release (null, null, connection);} Dao dao = new dao ();//string sql1 = "update users set Balance = balance-500 where id = 1 ";//string sql2 = " UPDATE Users set balance = balance+500 where id = 2 ";////dao.update (SQL2);// Dao.update (SQL1);} Public static void update (Connection connection,string sql,object ...args) { preparedstatement preparedstatement = null;try {System.out.println (Connection.getautocommit ());p reparedstatement = connection.preparestatement (SQL) ; for (int i = 0 ; i < args.length ; i ++) { Preparedstatement.setobject (I+1, args[i]);} Preparedstatement.executeupdate ();} catch (exception e) {e.printstacktrace ();} Finally{jdbctools.release (Null, preparedstatement, null);}}}
The above is the code when the error, should be no problem, is to learn the transaction written test code, but has not been able to achieve rollback.
Just say the solution, because the MySQL database default table does not support transactional rollback ...
Modifying the table type to InnoDB is possible.
MySQL database cannot be rolled back using transaction