標籤:
package mysql;import java.sql.Connection;import java.sql.SQLException;import java.sql.Savepoint;import java.sql.Statement;import org.junit.Test;//事物特性ACID//原子性,指事務中的操作要麼都發生,要麼都不發生//一致性。指事務前後資料的完整性必須保持一致(甲乙2人總額2000元,甲轉賬乙100元後,轉賬後總額還是2000元)//隔離性。多個事務並發訪問資料庫的時候,一個事務間的操作不能干擾其他事務,要相互隔離//持久性:指事務一旦提交(commit),對資料庫的改變是持久的,即使資料庫故障也不應對資料有影響//資料庫的隔離等級Seraializable(序列化,最進階別,能處理各種問題,但資料庫效率低下),repeated read,read commit,read uncommit/*create table account(id int primary key auto_increment,name varchar(20),price int);/* * 事務,要麼執行,要不執行 * start transaction update account set price=price-100 where name=‘a‘; update account set price=price+100 where name=‘b‘; * sql2語句 * commit(一定要執行commit才生效,不然復原) */public class 事務 {@Testpublic void test1() throws SQLException{Statement s=null;Connection con=DBHelper.getConnection();try{con.setAutoCommit(false);//不能一條一條執行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; //這邊有錯,程式自動復原s=con.createStatement();s.executeUpdate(sql2);con.commit();System.out.println("success....");}catch (Exception e) {con.rollback();//自動復原} }@Testpublic void test2() throws SQLException //手動復原事務,假如第二條sql執行錯誤,程式復原,讓第一條sql正常插入資料庫{Statement s=null;Connection con=DBHelper.getConnection();Savepoint p=null;try{con.setAutoCommit(false);//不能一條一條執行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(); //儲存點 int i=12/0; //這邊出錯了,上一條依然插入資料庫 s=con.createStatement();s.executeUpdate(sql2);s=con.createStatement();s.executeUpdate(sql3);con.commit();System.out.println("success....");}catch (Exception e) {con.rollback(p); //復原到第一個,第一個要執行con.commit(); //手動復原一定要提交}}}
mysql事務的四大特性與簡單運用