Public class TransactionTest {public static void main (String [] args) throws Exception {Connection conn = ConnectionFactory. getInstance (). getLocalConnection (); int money = 0; ResultSet rt = null; try {conn. setAutoCommit (false); Statement st = conn. createStatement (); String addMoneySql = "update test_user set money = money + 50 where uid = 1;"; int flag01_st.exe cuteUpdate (addMoneySql); System. out. println (flag0); String Export cemoneysql = "update test_user set money = money-50 where uid = 3"; int flag11_st.exe cuteUpdate (using cemoneysql); System. out. println (flag1); String queryMoneySql = "select money from test_user where uid = 3" using rt1_st.exe cuteQuery (queryMoneySql); if (rt. next () {money = rt. getInt ("mone"); // here the field is intentionally typed incorrectly to verify how java executes the transaction. The original field is moneySystem. out. println (money);} if (money <= 700) {throw new RuntimeException ("no more than 3, don't remit"); // throw Exception, rollback operation in exception handling} conn. commit ();} catch (Exception e) {e. printStackTrace (); // print the exception thrown above, otherwise it will not be displayed. If (conn! = Null) {conn. rollback ();}}}}
Run this code. The result is:
At com. mysql. jdbc. SQLError. createSQLException (SQLError. java: 910)
At com. mysql. jdbc. ResultSet. findColumn (ResultSet. java: 987)
At com. mysql. jdbc. ResultSet. getInt (ResultSet. java: 2749)
At TransactionTest. main (TransactionTest. java: 26)
When an exception occurs, catch the exception and perform the rollback operation to view the database. The database data has not changed. However, according to the results of update execution, update is executed. This shows the java execution strategy for processing database transactions: execute one sentence first (the basic data of the next sentence is the data of the last statement, rather than the actual data of the database ), when a rollback occurs, the database rollback is directly notified. After the database is rolled back, java is not notified, so the execution result is inconsistent with the database data.