MySQL autocommit 控制是否开启隐式事务

查看状态

mysql> show variables like '%autocommit%';

开启自动提交

mysql> set autocommit=1;

关闭自动提交

使用commit提交事务操作,或者使用rollback回滚操作

配置文件my.cnf添加:(默认为1)

[mysqld]
autocommit=0

配置用户登录时关闭autocommit,为安全起见该设置root用户不受影响,普通用户会关闭

[mysqld]
init_connect='set autocommit=0'

当前session关闭autocommit

mysql> set @@session.autocommit=0;

global级别关闭autocommit

mysql> set @@global.autocommit=0;

使用示例

创建普通用户:

mysql> create user tom identified by 'tom';
mysql> grant all on prod.* to 'tom’@localhost' identified by 'tom';
mysql> flush privileges;

普通用户登录

> mysql -utom -ptom
mysql> use mysql; #没有权限
mysql> use prod;
mysql> set autocommit=0;
mysql> show variables like '%commit%';

创建测试表

mysql> create table t1(id int,name varchar(10));
mysql> insert into t1 values(1,'tom');
mysql> select * from t1; #查询到一条数据
mysql> rollback; #事务回滚
mysql> select * from t1; #查询到0条数据