在MySQL中,事務(wù)就是一個(gè)邏輯工作單元的一系列步驟。事務(wù)是用來保證數(shù)據(jù)操作的安全性。
事務(wù)的特征:
1.Atomicity(原子性)
2.Consistency(穩(wěn)定性,一致性)
3.Isolation(隔離性)
4.Durability(可靠性)
注:事務(wù)只針對(duì)對(duì)數(shù)據(jù)數(shù)據(jù)產(chǎn)生影響的語句有效。
| show engines //查看mysql鎖支持的數(shù)據(jù)引擎 |
MyISAM不支持事物,InnoDB支持事物
默認(rèn)情況下,MySQL將以自動(dòng)提交模式運(yùn)行,這意味著沒一條小命令都將當(dāng)做一個(gè)只有一條命令的事物來執(zhí)行。
如果要讓mysql支持支持事務(wù),只需要修改數(shù)據(jù)引擎(alter table person type=INNODB)
使用start transaction或者begin命令來開啟一個(gè)事物,使用commit,或者rollback來結(jié)束事物。
事物的結(jié)束:事物除了commit,rollback會(huì)結(jié)束外,使用DDL或者DCL語句也會(huì)結(jié)束。
保存點(diǎn):通過保存點(diǎn)機(jī)制:用戶可以在事物里用savepoint name命令設(shè)置一些保存點(diǎn),以后用戶在使用rollback to savepoint name結(jié)束事物時(shí),name之前的數(shù)據(jù)保存,之后的數(shù)據(jù)不保存。
| mysql使用事務(wù)的關(guān)鍵字begin //打開一個(gè)事務(wù)commit //提交到數(shù)據(jù)庫(kù)rollback //取消操作savepoint //保存,部分取消,部分提交alter table person type=INNODB //修改數(shù)據(jù)引擎 |
示例如下:
| beginupdate person set name='efgh' where id =10select * from personrollbackselect * from person |
示例如下:
| alter table person type=INNODBbeginupdate person set name='efgh' where id =10select * from personcommitselect * from personbegindelete from person where id=21update person set name='efgh' where id =10commit/rollback |
針對(duì)上面部分提交,必須用到保存點(diǎn)
保存點(diǎn)注意:
1.只能取消到某個(gè)保存點(diǎn) rollback to savepoint p1
2.不能提交某個(gè)保存 commit to savepoint p2//錯(cuò)誤寫法
3.最后commit 把未取消的保存點(diǎn)去不提交到數(shù)據(jù)
事務(wù)保存點(diǎn)使用例子:
| begin;update score set score=40 where scoreid=1;savepoint s1;update score set score=50 where scoreid=2;select * from score;rollback to savepoint s1;select * from score;commit; |
新聞熱點(diǎn)
疑難解答
圖片精選