事務就是一個邏輯工作單元的一系列步驟。事務是用來保證資料操作的安全性
事務的特徵:
Atomicity(原子性)
Consistency(穩定性,一致性)
Isolation(隔離性)
Durability(可靠性)
【事務只針對對資料資料產生影響的語句有效】
show engines //查看mysql鎖支援的資料引擎
MyISAM不支援事物,InnoDB支援事物
預設情況下,MySQL將以自動認可模式運行,這意味著沒一條小命令都將當做一個只有一條命令的事物來執行。
如果要讓mysql支援支援事務,只需要修改資料引擎(alter table person type=INNODB)
使用start transaction或者begin命令來開啟一個事物,使用commit,或者rollback來結束事物。
事物的結束:事物除了commit,rollback會結束外,使用DDL或者DCL語句也會結束。
儲存點:通過儲存點機制:使用者可以在事物裡用savepoint name命令設定一些儲存點,以後使用者在使用rollback to savepoint name結束事物時,name之前的資料儲存,之後的資料不儲存。
mysql使用事務的關鍵字
1.begin //開啟一個事務
2.commit //提交到資料庫
3.rollback //取消操作
4.savepoint //儲存,部分取消,部分提交
alter table person type=INNODB //修改資料引擎
樣本:
begin
update person set name='efgh' where id =10
select * from person
rollback
select * from person
樣本:
alter table person type=INNODB
begin
update person set name='efgh' where id =10
select * from person
commit
select * from person
begin
delete from person where id=21
update person set name='efgh' where id =10
commit/rollback
針對上面部分提交,必須用到儲存點
儲存點注意:
1.只能取消到某個儲存點 rollback to savepoint p1
2.不能提交某個儲存 commit to savepoint p2//錯誤寫法
3.最後commit 把未取消的儲存點去不提交到資料
事務儲存點使用例子
1. begin;
2. update score set score=40 where scoreid=1;
3. savepoint s1;
4. update score set score=50 where scoreid=2;
5. select * from score;
6. rollback to savepoint s1;
7. select * from score;
8. commit;