在 MySQL 命令行的默认设置下,事务都是自动提交的,即执行 SQL 语句后就会马上执行 COMMIT 操作。因此要显式地开启一个事务务须使用命令 BEGIN 或 START TRANSACTION,或者执行命令 SET AUTOCOMMIT=0,用来禁止使用当前会话的自动提交。
1、用 BEGIN, ROLLBACK, COMMIT来实现
2、直接用 SET 来改变 MySQL 的自动提交模式:
select * from student; -- 开始事务 start transaction; -- 下边两条语句要在这个标签里边 (事务语句) delete from student where s_id = 1; select * from student; -- 回滚事务 rollback; -- 提交 commit; select * from student; select * from student; -- 开始事务 start transaction; -- 下边两条语句要在这个标签里边 (事务语句) delete from student where s_id = 2; -- 回滚到保存点 savepoint del1: delete from student where s_id = 3; select * from student; -- 回滚到保存点 ROLLBACK del1; -- s_id = 2;会删除 s_id = 3 不删除; select * from student; select * from student; set autocommit = 0; #不自动提交 START TRANSACTION; #开始事务 delete from student where s_id = 8; select * from student; end TRANSACTION; #提交事务 select * from student;
-- 提交操作(事务成功) mysql> start transaction;#手动开启事务 mysql> insert into t_user(name) values('pp'); mysql> commit;#commit之后即可改变底层数据库数据 mysql> select * from t_user; +----+------+ | id | name | +----+------+ | 1 | jay | | 2 | man | | 3 | pp | +----+------+ 3 rows in set (0.00 sec) -- 回滚操作(事务失败) mysql> start transaction; mysql> insert into t_user(name) values('yy'); mysql> rollback; mysql> select * from t_user; +----+------+ | id | name | +----+------+ | 1 | jay | | 2 | man | | 3 | pp | +----+------+ 3 rows in set (0.00 sec)
mysql> use RUNOOB; Database changed mysql> CREATE TABLE runoob_transaction_test( id int(5)) engine=innodb; # 创建数据表 Query OK, 0 rows affected (0.04 sec) mysql> select * from runoob_transaction_test; Empty set (0.01 sec) mysql> begin; # 开始事务 Query OK, 0 rows affected (0.00 sec) mysql> insert into runoob_transaction_test value(5); Query OK, 1 rows affected (0.01 sec) mysql> insert into runoob_transaction_test value(6); Query OK, 1 rows affected (0.00 sec) mysql> commit; # 提交事务 Query OK, 0 rows affected (0.01 sec) mysql> select * from runoob_transaction_test; +------+ | id | +------+ | 5 | | 6 | +------+ 2 rows in set (0.01 sec) mysql> begin; # 开始事务 Query OK, 0 rows affected (0.00 sec) mysql> insert into runoob_transaction_test values(7); Query OK, 1 rows affected (0.00 sec) mysql> rollback; # 回滚 Query OK, 0 rows affected (0.00 sec) mysql> select * from runoob_transaction_test; # 因为回滚所以数据没有插入 +------+ | id | +------+ | 5 | | 6 | +------+ 2 rows in set (0.01 sec) mysql>