mysq参数sql_safe_updates限制范围

本文介绍MySQL中通过设置sql_safe_updates参数来防止误更新或删除数据的方法。此参数开启后,能有效避免全表更新或删除操作,保障数据安全。文章详细解释了不同版本的配置方式及适用的SQL语句条件。

         在mysql运维中出现过不少因为update/delete条件错误导致数据被误更新或者删除的case,为避免类似问题的发生,可以用sql_safe_updates参数来对update/delete做限制。这个参数设置为on后,可防止因程序bug或者DBA手工误操作导致的整个表被更新或者删除的情况。

  设置这个参数时需要注意一下几点:

           a、设置前需要确认程序中所有的update和delete都符合sql_safe_updates的限制规范,不然程序会报错。

           b、5.0,5.1都是session级别的,5.6是global&session级别;低版本的数据库只能在程序创建session时设置带上set sql_safe_updates=on;高版本的数据库可以直接set global set sql_safe_updates=on,设置完成后让程序重连后生效。

限制规范:

示例表结构:

CREATE TABLE `delay_monitor` (
 `id` int(11) NOT NULL,
 `Ftime` datetime DEFAULT NULL,
 `Fgtid` varchar(128) NOT NULL DEFAULT '',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin​

1、update

a、报错条件:不带where、带where无索引、where条件为常量

     不带where:update delay_monitor set Ftime=now();

      带where无索引:update delay_monitor set Ftime=now() where Fgtid='test';

      where条件为常量:update delay_monitor set Ftime=now() where 1;

 b、执行条件:带where带索引、不带where+带limit、带where无索引+limit、带where有索引+limit、where条件为常量+limit

       带where带索引:update delay_monitor set Ftime=now() where id=2;

       不带where+带limit: update delay_monitor set Ftime=now()  limit 1;

       带where无索引+limit:update delay_monitor set Ftime=now() where Fgtid='test' limit 1;

       带where有索引+limit:update delay_monitor set Ftime=now() where id =2 limit1;

        where条件为常量+limit:update delay_monitor set Ftime=now() where 1 limit 1;

 2、delete

 相对于update,delelte的限制会更为严格;where条件为常量或者为空,将不予执行。

a、报错条件:不带where、带where无索引、不带where+带limit、where条件为常量、where条件为常量+limit

      不带where:delete delay_monitor set Ftime=now();

      带where无索引:delete delay_monitor set Ftime=now() where Fgtid='test';

      不带where+带limit: delete delay_monitor set Ftime=now()  limit 1;

      where条件为常量:delete delay_monitor set Ftime=now() where 1;

      where条件为常量+limit:delete delay_monitor set Ftime=now() where 1 limit 1; 

b、执行条件:带where带索引、带where无索引+limit、带where有索引+limt

      带where带索引:delete delay_monitor set Ftime=now() where id=2;

      带where无索引+limit:delete delay_monitor set Ftime=now() where Fgtid='test' limit 1;

      带where有索引+limit:delete delay_monitor set Ftime=now() where id =2 limit1;

总结如下表:key表示所有、const表示常量

操作 no wherewhere keywhere nokey limitwhere nokey+limitwhere key+limit     where constwhere const+limit
delete    NOYESNONOYESYESNO    NO
updateNOYESNOYESYESYESNOYES

   

 

转载于:https://www.cnblogs.com/Cherie/p/7658189.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值