在 MySQL 命令行的默认设置下,事务都是自动提交的,即执行 SQL 语句后就会马上执行 COMMIT 操作。因此要显式地开启一个事务务须使用命令 BEGIN 或 START TRANSACTION,或者执行命令 SET AUTOCOMMIT=0,用来禁止使用当前会话的自动提交。
事务控制语句:
-
BEGIN 或 START TRANSACTION 显式地开启一个事务;
-
COMMIT 也可以使用 COMMIT WORK,不过二者是等价的。COMMIT 会提交事务,并使已对数据库进行的所有修改成为永久性的;
-
ROLLBACK 也可以使用 ROLLBACK WORK,不过二者是等价的。回滚会结束用户的事务,并撤销正在进行的所有未提交的修改;
-
SAVEPOINT identifier,SAVEPOINT 允许在事务中创建一个保存点,一个事务中可以有多个 SAVEPOINT;
-
RELEASE SAVEPOINT identifier 删除一个事务的保存点,当没有指定的保存点时,执行该语句会抛出一个异常;
-
ROLLBACK TO identifier 把事务回滚到标记点;
-
SET TRANSACTION 用来设置事务的隔离级别。InnoDB 存储引擎提供事务的隔离级别有READ UNCOMMITTED、READ COMMITTED、REPEATABLE READ 和 SERIALIZABLE。
MYSQL 事务处理主要有两种方法:
1、用 BEGIN, ROLLBACK, COMMIT来实现
- BEGIN 开始一个事务
- ROLLBACK 事务回滚
- COMMIT 事务确认
2、直接用 SET 来改变 MySQL 的自动提交模式:
- SET AUTOCOMMIT=0 禁止自动提交
- SET AUTOCOMMIT=1 开启自动提交
数据库事务操作实例:
mysql> select * from stu; +------+----------+------+---------+---------+ | id | username | math | english | chinese | +------+----------+------+---------+---------+ | 1 | steven | 100 | 100 | 99 | | 2 | henry | 60 | 60 | 60 | | 3 | lucky | 90 | 90 | 90 | | 4 | eric | 99 | 88 | NULL | +------+----------+------+---------+---------+ mysql> begin; Query OK, 0 rows affected (0.01 sec) mysql> insert into stu values(5,'darren',98,99,90); Query OK, 1 row affected (0.02 sec) mysql> commit; Query OK, 0 rows affected (0.00 sec) mysql> select * from stu; +------+----------+------+---------+---------+ | id | username | math | english | chinese | +------+----------+------+---------+---------+ | 1 | steven | 100 | 100 | 99 | | 2 | henry | 60 | 60 | 60 | | 3 | lucky | 90 | 90 | 90 | | 4 | eric | 99 | 88 | NULL | | 5 | darren | 98 | 99 | 90 | +------+----------+------+---------+---------+ 5 rows in set (0.00 sec)
回滚实例:
mysql> begin; Query OK, 0 rows affected (0.00 sec) mysql> insert into stu values(5,'toto',98,99,90); Query OK, 1 row affected (0.00 sec) mysql> select * from stu; +------+----------+------+---------+---------+ | id | username | math | english | chinese | +------+----------+------+---------+---------+ | 1 | steven | 100 | 100 | 99 | | 2 | henry | 60 | 60 | 60 | | 3 | lucky | 90 | 90 | 90 | | 4 | eric | 99 | 88 | NULL | | 5 | darren | 98 | 99 | 90 | | 5 | toto | 98 | 99 | 90 | +------+----------+------+---------+---------+ 6 rows in set (0.00 sec) mysql> rollback; Query OK, 0 rows affected (0.00 sec) mysql> select * from stu; +------+----------+------+---------+---------+ | id | username | math | english | chinese | +------+----------+------+---------+---------+ | 1 | steven | 100 | 100 | 99 | | 2 | henry | 60 | 60 | 60 | | 3 | lucky | 90 | 90 | 90 | | 4 | eric | 99 | 88 | NULL | | 5 | darren | 98 | 99 | 90 | +------+----------+------+---------+---------+ 5 rows in set (0.00 sec)