事务的理解
事務的概念
事務是一組SQL組成的邏輯處理單元,通常有四個特性,簡稱ACID:
原子性(Atomic):數(shù)據(jù)庫事務是不可分割的工作單位。事務中的SQL語句要么都執(zhí)行成功,要么都執(zhí)行失敗。
一致性(Consistency):數(shù)據(jù)庫事務不能破壞數(shù)據(jù)庫的完整性和業(yè)務邏輯的一致性。例如銀行轉(zhuǎn)賬業(yè)務,A給B轉(zhuǎn)賬,不管轉(zhuǎn)賬失敗還是成功,A和B的總存款不能變。
隔離性(Isolation):在并發(fā)的環(huán)境中,當不同的事務操作相同的數(shù)據(jù)時,每個事務都有各自完整的數(shù)據(jù)空間。
持久性(Durability):只要事務提交成功,對數(shù)據(jù)庫做的更改必須永久的保存下來。即使數(shù)據(jù)庫奔潰或者數(shù)據(jù)庫重啟,也能恢復到事務提交后的狀態(tài)。
事務的隔離性
1、我們先看看如果不考慮事務的隔離性,會發(fā)生的幾種問題:
(1)臟讀
臟讀是指在一個事務讀取了另一個未提交的數(shù)據(jù)。
當一個事務正在多次修改某個數(shù)據(jù),而在這個事務中這多次的修改都還未提交,這時一個并發(fā)的事務來訪問該數(shù)據(jù),就會造成兩個事務得到的數(shù)據(jù)不一致。例如:用戶A向用戶B轉(zhuǎn)賬100元,對應SQL命令如下
update account set money=money+100 where name=’B’; (此時A通知B)update account set money=money - 100 where name=’A’;當只執(zhí)行第一條SQL時,A通知B查看賬戶,B發(fā)現(xiàn)確實錢已到賬(此時即發(fā)生了臟讀),而之后無論第二條SQL是否執(zhí)行,只要該事務不提交,則所有操作都將回滾,那么當B以后再次查看賬戶時就會發(fā)現(xiàn)錢其實并沒有轉(zhuǎn)。
(2)不可重復讀
不可重復讀是指在對于數(shù)據(jù)庫中的某一行數(shù)據(jù),一個事務范圍內(nèi)多次查詢卻返回了不同的數(shù)據(jù)值。原因是另外一個事務做了更新操作。
例如事務T1在讀取某一數(shù)據(jù),而事務T2立馬修改了這個數(shù)據(jù)并且提交事務給數(shù)據(jù)庫,事務T1再次讀取該數(shù)據(jù)就得到了不同的結(jié)果,發(fā)生了不可重復讀。
不可重復讀和臟讀的區(qū)別是,臟讀是某一事務讀取了另一個事務未提交的臟數(shù)據(jù),而不可重復讀則是讀取了前一事務提交的數(shù)據(jù)。
在某些情況下,不可重復讀并不是問題,比如我們多次查詢某個數(shù)據(jù)當然以最后查詢得到的結(jié)果為主。但在另一些情況下就有可能發(fā)生問題,例如對于同一個數(shù)據(jù)A和B依次查詢就可能不同,A和B就可能打起來了……
(3)虛讀(幻讀)
幻讀是指一個事務內(nèi)的多次查詢返回的結(jié)果集不一致。原因是另外一個事務做了插入或者刪除操作。
? ? ? ?例如事務T1對一個表中所有的行的某個數(shù)據(jù)項做了從“1”修改為“2”的操作,這時事務T2又對這個表中插入了一行數(shù)據(jù)項,而這個數(shù)據(jù)項的數(shù)值還是為“1”并且提交給數(shù)據(jù)庫。而操作事務T1的用戶如果再查看剛剛修改的數(shù)據(jù),會發(fā)現(xiàn)還有一行沒有修改,其實這行是從事務T2中添加的,就好像產(chǎn)生幻覺一樣,這就是發(fā)生了幻讀。
幻讀和不可重復讀都是讀取了另一個事務已提交的數(shù)據(jù)(這點和臟讀不同),所不同的是不可重復讀查詢的都是同一行數(shù)據(jù),是另外一個事務update操作導致出現(xiàn)的問題。而幻讀針對的是一批數(shù)據(jù)整體(比如數(shù)據(jù)的個數(shù)),是另外一個事務insert或delete操作導致出現(xiàn)的問題。
2、現(xiàn)在來看看MySQL數(shù)據(jù)庫為我們提供的四種隔離級別:
① Serializable (串行化):可避免臟讀、不可重復讀、幻讀的發(fā)生。
② Repeatable read (可重復讀):可避免臟讀、不可重復讀的發(fā)生。
③ Read committed (提交讀):可避免臟讀的發(fā)生。
④ Read uncommitted (未提交讀):最低級別,任何情況都無法保證。
以上四種隔離級別最高的是Serializable級別,最低的是Read uncommitted級別,當然級別越高,執(zhí)行效率就越低。像Serializable這樣的級別,就是以鎖表的方式(類似于Java多線程中的鎖)使得其他的線程只能在鎖外等待,所以平時選用何種隔離級別應該根據(jù)實際情況。在MySQL數(shù)據(jù)庫中默認的隔離級別為Repeatable read (可重復讀)。
注:在mysql5.6以上版本引入了MVCC,在Repeatable read隔離級別下已經(jīng)不存在幻讀問題了。
在MySQL數(shù)據(jù)庫中,支持上面四種隔離級別,默認的為Repeatable read (可重復讀);而在Oracle數(shù)據(jù)庫中,只支持Serializable (串行化)級別和Read committed (提交讀)這兩種級別,其中默認的為Read committed級別。
驗證Oracle數(shù)據(jù)庫的隔離級別
1、證明一個事務不會讀取到另一個事務未提交的數(shù)據(jù),即證明oracle數(shù)據(jù)庫不會發(fā)生臟讀
package org.cc;import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;public class JDBCDemo {public static void main(String[] args) throws InterruptedException {Thread updateThread = new Thread(new UpdateAndAdd());//修改和插入數(shù)據(jù)后,1分鐘后再提交數(shù)據(jù)Thread readData = new Thread(new ReadData());//讀取數(shù)據(jù),看看能否讀取到上面事務未提交的數(shù)據(jù)updateThread.start();Thread.sleep(2000);//停頓2秒,保證前一個事務已經(jīng)操作了數(shù)據(jù)庫readData.start();}private static Connection getConn() throws ClassNotFoundException, SQLException{Class.forName("oracle.jdbc.driver.OracleDriver");return DriverManager.getConnection("jdbc:oracle:thin:@//127.0.0.1:1521/orcl", "scott", "tigger");}static class UpdateAndAdd implements Runnable {@Overridepublic void run() {Connection conn = null;Statement state = null;try {conn = getConn();conn.setAutoCommit(false);state = conn.createStatement();System.out.println("即將操作數(shù)據(jù)庫!");state.executeUpdate("update emp set comm=1000 where ENAME='SMITH'");state.executeUpdate("insert into emp values('6666','lipiao','CLERK','7902',to_date('20200725','yyyymmdd'),800,1000,'20')");Thread.sleep(10000);//一分鐘后再提交事務,另外一個線程看能夠讀取到這些數(shù)據(jù)conn.commit();} catch (SQLException | ClassNotFoundException | InterruptedException e) {e.printStackTrace();} finally {try {if (state != null) {state.close();}if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}}}static class ReadData implements Runnable{@Overridepublic void run() {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {conn = getConn();ps = conn.prepareStatement("select * from emp where ename in(?,?)");ps.setString(1, "SMITH");ps.setString(2, "lipiao");System.out.println("讀取數(shù)據(jù)");rs = ps.executeQuery();while(rs.next()){System.out.println("讀取到了一行數(shù)據(jù):comm:"+rs.getDouble("comm"));}} catch (SQLException | ClassNotFoundException e) {e.printStackTrace();} finally {try {if(rs!=null){rs.close();}if (ps != null) {ps.close();}if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}}} }2 證明會發(fā)生不可重復度和幻讀,意思說當前事務兩次讀取同一行記錄數(shù)據(jù)不一致(不可重復度,其他事務做了修改,并且提交了事務),當前事務第一次和第二次讀取的記錄數(shù)不一致(幻讀,其他事務有新增記錄,并且提交了事務)
package org.cc;import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;public class JDBCDemo2 {public static void main(String[] args) throws InterruptedException {Thread updateThread = new Thread(new UpdateAndAdd());//修改和插入數(shù)據(jù)Thread readData = new Thread(new ReadData());//兩次讀取數(shù)據(jù)readData.start();Thread.sleep(3000);updateThread.start();}private static Connection getConn() throws ClassNotFoundException, SQLException{Class.forName("oracle.jdbc.driver.OracleDriver");return DriverManager.getConnection("jdbc:oracle:thin:@//127.0.0.1:1521/orcl", "scott", "tigger");}static class UpdateAndAdd implements Runnable {@Overridepublic void run() {Connection conn = null;Statement state = null;try {conn = getConn();state = conn.createStatement();System.out.println("即將操作數(shù)據(jù)庫!");state.executeUpdate("update emp set comm=2000 where ENAME='SMITH'");state.executeUpdate("insert into emp values('6667','cc','CLERK','7902',to_date('20200725','yyyymmdd'),800,1000,'20')");} catch (SQLException | ClassNotFoundException e) {e.printStackTrace();} finally {try {if (state != null) {state.close();}if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}}}static class ReadData implements Runnable{@Overridepublic void run() {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {conn = getConn();ps = conn.prepareStatement("select * from emp where ename in(?,?)");ps.setString(1, "SMITH");ps.setString(2, "cc");System.out.println("第一次讀取數(shù)據(jù)");rs = ps.executeQuery();//先查詢while(rs.next()){System.out.println("讀取到了一行數(shù)據(jù):ename:"+rs.getString("ename")+",comm:"+rs.getDouble("comm"));}Thread.sleep(10000);//等另外一個事務提交System.out.println("另外一個事務提交后讀取數(shù)據(jù)");rs.close();rs = ps.executeQuery();//先查詢while(rs.next()){System.out.println("讀取到了一行數(shù)據(jù):ename:"+rs.getString("ename")+",comm:"+rs.getDouble("comm"));}} catch (SQLException | ClassNotFoundException | InterruptedException e) {e.printStackTrace();} finally {try {if(rs!=null){rs.close();}if (ps != null) {ps.close();}if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}}} }?
總結(jié)
- 上一篇: 嵌入式linux中的锁机制,跟涛哥一起学
- 下一篇: 【JAVA基础篇】枚举