1 回答

TA貢獻1775條經(jīng)驗 獲得超11個贊
什么是事務(wù)?
事務(wù)是邏輯上的一組操作,組成這組操作的各個單元,要不全都成功要不全都失敗,這個特性就是事務(wù)
注意:mysql數(shù)據(jù)支持事務(wù),但是要求必須是innoDB存儲引擎
解決這個問題:
mysql的事務(wù)解決這個問題,因為mysql的事務(wù)特性,要求這組操作,要不全都成功,要不全都失敗,這樣就避免了某個操作成功某個操作失敗。利于數(shù)據(jù)的安全
如何使用:
(1)在執(zhí)行sql語句之前,我們要開啟事務(wù) start transaction;
(2)正常執(zhí)行我們的sql語句
(3)當(dāng)sql語句執(zhí)行完畢,存在兩種情況:
1,全都成功,我們要將sql語句對數(shù)據(jù)庫造成的影響提交到數(shù)據(jù)庫中,committ
2,某些sql語句失敗,我們執(zhí)行rollback(回滾),將對數(shù)據(jù)庫操作趕緊撤銷
(注意:mysql數(shù)據(jù)支持事務(wù),但是要求必須是innoDB存儲引擎)
mysql> create table bank(name varchar(20),money decimal(5,1))engine=innodb defau
lt charset=utf8;
mysql> inset into bank values('shaotuo',1000),('laohu',5000);
mysql> select*from bank;
+---------+--------+
| name | money |
+---------+--------+
| shaotuo | 1000.0 |
| laohu | 5000.0 |
+---------+--------+
------沒有成功“回滾”執(zhí)行rollback
mysql> start transaction; //開啟事務(wù)
Query OK, 0 rows affected (0.00 sec)
mysql> update bank set money=money+500 where name='shaotuo';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> update bank set moey=money-500 where name='laohu';
ERROR 1054 (42S22): Unknown column 'moey' in 'field list'
mysql> rollback; //只要有一個不成功,執(zhí)行rollback操作
Query OK, 0 rows affected (0.01 sec)
mysql> select*from bank;
+---------+--------+
| name | money |
+---------+--------+
| shaotuo | 1000.0 |
| laohu | 5000.0 |
+---------+--------+
------成功之后 進行commit操作
mysql> start transaction; //開啟事務(wù)
Query OK, 0 rows affected (0.00 sec)
mysql> update bank set money=money+500 where name='shaotuo';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> update bank set money=money-500 where name='laohu';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> commit; //兩個都成功后執(zhí)行commit(只要不執(zhí)行commit,sql語句不會對真實的數(shù)據(jù)庫造成影響)
Query OK, 0 rows affected (0.05 sec)
mysql> select*from bank;
+---------+--------+
| name | money |
+---------+--------+
| shaotuo | 1500.0 |
| laohu | 4500.0 |
+---------+--------+
- 1 回答
- 0 關(guān)注
- 952 瀏覽
添加回答
舉報