Transaction processing-rollback (transfer operation)

Source: Internet
Author: User

JDBC Transaction processing-Four principles

Atomic Nature
Consistency
Isolation of
Durability

The first step: realize the transfer operation

Assuming that in the account, Galen has a balance of 5000 yuan, Nerf has a balance of 2000 yuan,

Galen wants to transfer 1000 yuan to nerf.

public static void Outmoney (Connection conn,string name,int account) throws sqlexception{string sql= "Update t_account set Balance=balance-? where name=? "; PreparedStatement pst=conn.preparestatement (SQL);p St.setint (1, account);p st.setstring (2, name); int result= Pst.executeupdate ();p st.close ();} public static void Inmoney (Connection conn,string name,int account) throws sqlexception{string sql= "Update T_account set B Alance=balance+? where name=? "; PreparedStatement pst=conn.preparestatement (SQL);p St.setint (1, account);p st.setstring (2, name); int result= Pst.executeupdate ();p st.close ();}

  

System.out.println ("Galen is transferring $1000 to Nerf");//Transfer operation try {Outmoney (conn, "Galen", +), Inmoney (conn, "Nerf", +);} catch ( SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally{try {System.out.println ("Transfer successful! "); Conn.close ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}

Run:

The normal transfer was successful.

Assume that the public static void Inmoney (Connection conn,string name,int account) is running unexpectedly.

Artificial construction accident

Then run the program

View data for a database

Galen 1000 yuan Less, Nerf balance has not changed!

In this way, Nerf on the pit!!!

Improved

The required functions

Con.setautocommit (FALSE); Cancel Auto-Commit

Con.rollback (); Rolling back

Con.commit (); Commit a transaction

Transaction processing-rollback (transfer operation)

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.