如果在生產環境中使用UPDATE語句更新表數據,此時如果忘記攜帶本應該添加的WHERE條件,那么。。Oh,no…后果可能不堪設想。那么有沒有什么辦法可以阻止這樣的事情發生,又不使用任何的審核工具呢。。。辦法當然是有的
sql_safe_updates
sql_safe_updates這個MySQL自帶的參數就可以完美的解決我們的問題,並且該參數是可以在線變更的哦~當該參數開啟的情況下,你必須要在UPDATE語句后攜帶WHERE條件,否則就會報出ERROR。。
舉個栗子
# sql_safe_updates=0,即未開啟 root@127.0.0.1 : test 07:58:34> set sql_safe_updates=0; Query OK, 0 rows affected (0.00 sec) root@127.0.0.1 : test 07:58:43> show variables like 'sql_safe_updates'; +------------------+-------+ | Variable_name | Value | +------------------+-------+ | sql_safe_updates | OFF | +------------------+-------+ 1 row in set (0.00 sec) root@127.0.0.1 : test 07:58:55> select * from t; +-------+ | pd | +-------+ | hello | | mysql | +-------+ 2 rows in set (0.00 sec) root@127.0.0.1 : test 07:58:59> begin; Query OK, 0 rows affected (0.00 sec) root@127.0.0.1 : test 07:59:04> update t set pd='MySQL'; Query OK, 2 rows affected (0.00 sec) Rows matched: 2 Changed: 2 Warnings: 0 root@127.0.0.1 : test 07:59:12> select * from t; +-------+ | pd | +-------+ | MySQL | | MySQL | +-------+ 2 rows in set (0.00 sec) # sql_safe_updates=1,即開啟 root@127.0.0.1 : test 08:00:00> set sql_safe_updates=1; Query OK, 0 rows affected (0.00 sec) root@127.0.0.1 : test 08:00:11> show variables like 'sql_safe_updates'; +------------------+-------+ | Variable_name | Value | +------------------+-------+ | sql_safe_updates | ON | +------------------+-------+ 1 row in set (0.00 sec) root@127.0.0.1 : test 08:00:16> select * from t; +-------+ | pd | +-------+ | hello | | mysql | +-------+ 2 rows in set (0.00 sec) root@127.0.0.1 : test 08:00:25> begin; Query OK, 0 rows affected (0.00 sec) root@127.0.0.1 : test 08:00:27> update t set pd='MySQL'; ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
如上屬的例子所示,當參數sql_safe_updates開啟的時候,UPDATE語句不攜帶WHERE條件將會爆出一個錯誤。。所以小心使用UPDATE語句是真的很重要哇。。。