事务
1.概念
开启事务的语句,具体如下:
提交事务的语句,具体如下:
回滚事务的语句,具体如下:
例子:
mysql> CREATE TABLE account( id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(40),money FLOAT)ENGINE=InnoDB;
Query OK, 0 rows affected
mysql> INSERT INTO account(name,money) VALUES("a",1000),("b",1000);
Query OK, 2 rows affected
Records: 2 Duplicates: 0 Warnings: 0
注意: 在句子的最后要加引擎ENFINE=InnoDB,否则可能会导致后面操作不成功
mysql> START TRANSACTION; UPDATE account SET money=money-100 WHERE name="a"; UPDATE account SET money=money+100 WHERE name="b";COMMIT;
Query OK, 0 rows affected
Query OK, 1 row affected
Rows matched: 1 Changed: 1 Warnings: 0
Query OK, 1 row affected
Rows matched: 1 Changed: 1 Warnings: 0
Query OK, 0 rows affected
注意: 几个句子要写在一起,否则可能会导致后面操作不成功
mysql> SELECT *FROM account;
+----+------+-------+
| id | name | money |
+----+------+-------+
| 1 | a | 900 |
| 2 | b | 1100 |
+----+------+-------+
2 rows in set
2:事务的提交
下面就在之前的基础上开启一个事务,用UPDATE语句实现由b账户向a账户转100元的转账功能
mysql> START TRANSACTION;
UPDATE account SET money=money+100 WHERE name="a";
UPDATE account SET money=money-100 WHERE name="b";
Query OK, 0 rows affected
Query OK, 1 row affected
Rows matched: 1 Changed: 1 Warnings: 0
Query OK, 1 row affected
Rows matched: 1 Changed: 1 Warnings: 0
没有使用COMMIT语句,所以并没有提交事务
mysql> SELECT *FROM account;
+----+------+-------+
| id | name | money |
+----+------+-------+
| 1 | a | 1000 |
| 2 | b | 1000 |
+----+------+-------+
2 rows in set
此时再打开另一个命令界面,查询数据库中各账户余额信息
mysql> SELECT *FROM account;
+----+------+-------+
| id | name | money |
+----+------+-------+
| 1 | a | 900 |
| 2 | b | 1100 |
+----+------+-------+
2 rows in set
可以看到没有提交事务,只是自己的账户变了,而在别的的账户下查这些信息是没有任何变化的,还是原来的余额。
在原来第一个账户的基础上做下一个回滚实验,具体操作如下:
mysql> ROLLBACK;
Query OK, 0 rows affected
mysql> SELECT *FROM account;
+----+------+-------+
| id | name | money |
+----+------+-------+
| 1 | a | 900 |
| 2 | b | 1100 |
+----+------+-------+
2 rows in set
注意:没有提交事务的话,是可以回滚的,还可以变为未执行这次操作之前的账户余额
3:事务的隔离级别