mysql事務的四大特性與簡單運用

來源:互聯網
上載者:User

標籤:

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事務的四大特性與簡單運用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.