Package Mysql;import Java.sql.connection;import Java.sql.sqlexception;import java.sql.savepoint;import Java.sql.statement;import org.junit.test;//things feature acid//atomicity, which means that operations in a transaction either occur or do not occur//consistency. The integrity of the data before and after the transaction must be consistent (a B 2 total of 2000 yuan, a transfer of B 100 yuan, after the transfer amount is 2000 yuan)//isolation. When multiple transactions concurrently access the database, the operation between one transaction does not interfere with other transactions, to isolate//persistence: Refers to the transaction once committed, the changes to the database is persistent, even if the database failure should not affect the data/database isolation level seraializable (serialization, highest level, can handle various problems, but database inefficiency), repeated read,read commit,read uncommit/*create table account (ID int primary KEY auto_ Increment,name varchar (), price int);/* * transaction, either execute, or Execute * Start Transaction update account set PRICE=PRICE-100 where name = ' a '; Update account set price=price+100 where name= ' B '; * SQL2 statement * COMMIT (must execute commit to take effect, otherwise rollback) */public class Transaction {@Testpublic void Test1 () throws Sqlexception{statement S=null; Connection con=dbhelper.getconnection (); Try{con.setautocommit (false);//Cannot execute SqlString sql1= "update account set price=price-100 where name= ' a '; String sql2= "Update account set price=price+100 where name= ' B '"; S=con.createstatemENT (); s.executeupdate (SQL1); int i=8/0; This side is wrong, the program automatically rolls back s=con.createstatement (); s.executeupdate (SQL2); Con.commit (); SYSTEM.OUT.PRINTLN ("Success ..."); catch (Exception e) {con.rollback ();//Auto Rollback}} @Testpublic void Test2 () throws SQLException//manual rollback of the transaction, if the second SQL execution error, the program rollback, let the first A SQL normal insert database {Statement s=null; Connection con=dbhelper.getconnection (); SavePoint P=null;try{con.setautocommit (FALSE);//Cannot execute SqlString sql1= "update account set price=price-100 where name = ' A ' "; String sql2= "Update account set price=price+100 where name= ' B '"; String sql3= "Update account set price=price+100 where name= ' C '"; S=con.createstatement (); s.executeupdate (SQL1); P=con.setsavepoint (); Save Point int i=12/0; This is a mistake, the previous one is still inserted into the database s=con.createstatement (); s.executeupdate (SQL2); S=con.createstatement (); s.executeupdate (SQL3); Con.commit (); SYSTEM.OUT.PRINTLN ("Success ..."); catch (Exception e) {con.rollback (P);//Roll back to first, first to execute con.commit (); Manual rollback must be committed}}}
Four features and simple application of MySQL transaction