JDBC Series: (7) Using connection to manipulate transactions

Source: Internet
Author: User
Tags rollback savepoint

transaction ACID Properties
sequence number Special Description
1 Atom Sex (atomicity) atomicity means that a transaction is an indivisible unit of work that either occurs in a transaction or does not occur.
2 Consistency (consistency) The transaction must make the database Transitions from one consistent state to another.
3 Isolation (Isolation) transaction Isolation is multiple When the database is accessed concurrently, the database is opened for each user and cannot be disturbed by the operation data of other transactions, and the multiple concurrent transactions are isolated from each other.
4 Persistence (durability) persistence refers to a transaction Once committed, it changes the data in the database to be permanent, and then should not have any effect on it even if the database fails




Connection related methods of operational transactions
Serial Number Method function
1 void Setautocommit (Boolean autocommit) Set whether a transaction is automatically committed
If set to False, indicates that the transaction is committed manually.
2 void commit () () Committing transactions manually
3 void rollback () Rollback (When an exception occurs, all code that has executed successfully needs to fall back to the state before the transaction started.) )
4 SavePoint setsavepoint (String name) Create a savepoint in the current transaction


1. Use transactions

package com.rk.db.g_transaction;import java.sql.connection;import java.sql.preparedstatement; import java.sql.sqlexception;import com.rk.db.utils.jdbcutil;/** * //  transfer, using transaction  *   @author  rk * */public class demo01{public static void main ( String[] args) {connection conn = null;try{conn = jdbcutil.getconnection ();//  1, sets the transaction to submit Conn.setautocommit (false) manually, boolean flag = true; //indicates whether a SQL exception occurred TransferMoney (conn, 100,  "Zhang San",  "John Doe", flag);} catch  (sqlexception e) {System.out.println ("Transfer failed! TRY{// 2,   The exception, need to roll back the transaction conn.rollback (); SYSTEM.OUT.PRINTLN ("Rollback operation succeeded!!! ");} catch  (Sqlexception ex) {ex.printstacktrace ();}} FINALLY{// 3, all operations executed successfully,  COMMIT transaction try{conn.commit (); SYSTEM.OUT.PRINTLN ("Done! ");} catch  (sqlexception e) {e.printstacktrace ();} jdbcutil.closequietly (conn);}} /** *  Analog Bank transfer  *  @param  conn  database connection  *  @param  moneyNum  transfer amount  *  @param  userAdd  users who have received money   *  @param  userSub  Spending money users  *  @param  flag  whether to simulate sql exception exceptions, true to indicate False to indicate that the  *  @throws  sqlexception */private static void transfermoney not Present ( Connection conn, long moneynum, string useradd, string usersub,boolean  flag)  throws SQLException{PreparedStatement pstmtAdd = null; preparedstatement pstmtsub = null;try{string sqladdmoney =  "Update T_Bank  set money=money+? where username=? "; Pstmtadd = conn.preparestatement (Sqladdmoney);p Stmtadd.setlong (1, moneynum);p stmtadd.setstring ( 2, useradd);p stmtadd.executeupdate (); if (flag) {throw new sqlexception ("Error simulating SQL Execution");} string sqlsubmoney =  "Update t_bank set money=money-? where usernAme=? "; Pstmtsub = conn.preparestatement (Sqlsubmoney);p Stmtsub.setlong (1, moneynum);p stmtsub.setstring ( 2, usersub);p stmtsub.executeupdate ();} finally{jdbcutil.closequietly (Pstmtadd); jdbcutil.closequietly (pstmtsub);}}}



2. Using transactions, rollback to the specified code snippet

package com.rk.db.g_transaction;import java.sql.connection;import java.sql.preparedstatement; import java.sql.sqlexception;import java.sql.savepoint;import com.rk.db.utils.jdbcutil;/**  * //  transfer, using transaction,  rollback to the specified code snippet  *  @author  RK * */public class  Demo02{public static void main (String[] args) {connection conn = null; Savepoint sp = null;try{conn = jdbcutil.getconnection ();// 1, Set TRANSACTION to Manual commit Conn.setautocommit (False), TransferMoney (conn, 1000,  "John Doe",  "Zhang San", false);//  if failed, Roll back to this position sp = conn.setsavepoint (); boolean flag = true; //indicates whether the SQL exception TransferMoney is present ( conn, 500,  "Zhang San",  "John Doe", flag);} catch  (sqlexception e) {System.out.println ("Transfer failed! TRY{// 2,   exception, need to roll back   (rollback to the specified code snippet) conn.rollback (SP); SYSTEM.OUT.PRINTLN ("Rollback to specified location operation succeeded!!!" ");} catch  (Sqlexception ex) {ex.printstacktrace ();}} FINALLY{// 3, all operations executed successfully,  COMMIT transaction try{conn.commit (); SYSTEM.OUT.PRINTLN ("Done! ");} catch  (sqlexception e) {e.printstacktrace ();} jdbcutil.closequietly (conn);}} /** *  Analog Bank Transfer  *  @param  conn  database connection  *  @param  moneyNum  amount Transferred  *  @param  userAdd  users who receive money  *  @param  userSub  user  * @ for spending money param flag  whether the sql exception exception is simulated, true indicates that it appears, false indicates that no  *  @throws  sqlexception * /private static void transfermoney (connection conn, long moneynum, string  useradd, string usersub,boolean flag)  throws sqlexception{preparedstatement  pstmtAdd = null; preparedstatement pstmtsub = null;try{string sqladdmoney =  "Update T_Bank  set money=money+? where username=? "; Pstmtadd = conn.preparestatement (Sqladdmoney);p Stmtadd.setlong (1, moneynum);p STMTadd.setstring (2, useradd);p stmtadd.executeupdate (); if (flag) {throw new sqlexception ("Error simulating SQL Execution" );} string sqlsubmoney =  "Update t_bank set money=money-? where username=?"; Pstmtsub = conn.preparestatement (Sqlsubmoney);p Stmtsub.setlong (1, moneynum);p stmtsub.setstring ( 2, usersub);p stmtsub.executeupdate ();} finally{jdbcutil.closequietly (Pstmtadd); jdbcutil.closequietly (pstmtsub);}}}





JDBC Series: (7) Using connection to manipulate transactions

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.