JDBC Transaction processing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.