About transactions:
1. Multiple operations in one transaction should have a connection, and if each operation is in a different connection, the transaction cannot be rolled back.
2, the specific steps:
1), before the transaction begins, the automatic commit of the transaction should be canceled, that is, set Connection.setautocommit (false);
2), if the operation in the transaction succeeds, commit the transaction, i.e. Connection.commit ();
3), if an exception occurs during the execution of the transaction, the transaction is rolled back in the catch, that is, connection.rollback ();
1 @Test2 Public voidTesttransaction ()throwsException {3Connection Connection =NULL;4 Try{5Connection =jdbctools.getconnection ();6 System.out.println (connection);7Connection.setautocommit (false);8String sql = "Update user set balance = balance-500 WHERE id = 1";9 Update (CONNECTION,SQL);Ten Onesql = "Update user set balance = balance + where id = 2"; A Update (CONNECTION,SQL); - - connection.commit (); the -}Catch(Exception e) { - e.printstacktrace (); - Connection.rollback (); +}finally { -Jdbctools.releaseresource (NULL,NULL, connection); + } A at - } - - Public voidUpdate (Connection connection,string sql) { -PreparedStatement PreparedStatement =NULL; - Try { inPreparedStatement =connection.preparestatement (SQL); - Preparedstatement.execute (); to}Catch(Exception e) { + e.printstacktrace (); -}finally { theJdbctools.releaseresource (NULL, PreparedStatement,NULL); * } $}
JDBC Transaction processing