Mysql safety update 安全模式【 更新或删除数据操作】

Mysql safety update 安全模式【 更新或删除数据操作

在mysql中,如果在update和delete没有加上where条件,数据将会全部修改。不只是初识mysql的开发者会遇到这个问题,工作有一定经验的工程师难免也会忘记写入where条件。为了避免失误造成的数据全部修改和删除,可开启mysql的安全模式。
说明:在update/delete 语句在更新时,必须要添加where条件(索引列)
(1)、查询安全模式是否开启
连接到数据库后,查看当前mysql的安全模式的状态
mysql> show variables like 'sql_safe_updates';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| sql_safe_updates | OFF   |
+------------------+-------+
1 row in set (0.00 sec)
(2)、安全模式的开启与关闭
//全局临时生效
set global sql_safe_updates=1;           //安全模式打开状态
set global sql_safe_updates=0;          //安全模式关闭状态
永久生效:先引入init.sql ,再写入全局变量


vim /etc/my.cnf
.....
[mysqld]
init-file=/etc/init.sql
.....

[root@web etc]# vim /etc/init.sql 
set global sql_safe_updates=1;


重启数据库生效
systemctl restart mysqld


mysql> show variables like 'sql_safe_updates';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| sql_safe_updates | ON    |
+------------------+-------+
1 row in set (0.00 sec)
(3)、安全模式下模拟删除操作,不添加where 条件(索引列)
模拟往student 表里插入几条数据,再模拟删除
mysql> select * from student;
+----+--------+-----+---------+---------------------+----------+
| id | sname  | age | sgender | intime              | tel      |
+----+--------+-----+---------+---------------------+----------+
|  1 | fxkjnj |  24 | M       | 2022-02-01 12:14:15 | 11111111 |
|  2 | fxkjnj |  24 | M       | 2022-02-01 12:14:15 | 22222    |
|  3 | fxkjnj |  24 | M       | 2022-02-01 12:14:15 | 33333    |
|  4 | fxkjnj |  24 | M       | 2022-02-01 12:18:16 | 3333     |
+----+--------+-----+---------+---------------------+----------+
4 rows in set (0.00 sec)

mysql> delete from student;
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. 
mysql> 
(4)、安全模式下模拟updata操作,不添加where 条件(索引列)
mysql> select * from student;
+----+--------+-----+---------+---------------------+----------+
| id | sname  | age | sgender | intime              | tel      |
+----+--------+-----+---------+---------------------+----------+
|  1 | fxkjnj |  24 | M       | 2022-02-01 12:14:15 | 11111111 |
|  2 | fxkjnj |  24 | M       | 2022-02-01 12:14:15 | 22222    |
|  3 | fxkjnj |  24 | M       | 2022-02-01 12:14:15 | 33333    |
|  4 | fxkjnj |  24 | M       | 2022-02-01 12:18:16 | 3333     |
|  5 | fxkjnj |  24 | M       | 2022-02-01 12:22:21 | 23333    |
+----+--------+-----+---------+---------------------+----------+
5 rows in set (0.00 sec)

mysql> update student set age=25;
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column

上面的演示,在没有添加where 条件(索引列) 都会报错,这样就避免了一些失误


© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容