Mysql safety update 安全模式【 更新或删除数据操作】
本文最后更新于 2024-07-07,文章内容可能已经过时。
Mysql safety update 安全模式【 更新或删除数据操作】
在mysql中,如果在 update
和 delete
没有加上 where
条件,数据将会全部修改。
不只是初识mysql的开发者会遇到这个问题,工作有一定经验的工程师难免也会忘记写入where条件。为了避免失误造成的数据全部修改和删除,可开启mysql的安全模式。
说明:在update/delete 语句在更新时,必须要添加where条件(索引列)
1、查询安全模式是否开启
mysql> show variables like 'sql_safe_updates';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| sql_safe_updates | OFF |
+------------------+-------+
1 row in set (0.00 sec)
连接到数据库后,查看当前mysql的安全模式的状态
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 条件(索引列) 都会报错,这样就避免了一些失误
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 运维小弟
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果