1. 程式人生 > 實用技巧 >基於MySQL的-u選項實現如何最大程度防止人為誤操作MySQL資料庫

基於MySQL的-u選項實現如何最大程度防止人為誤操作MySQL資料庫

在mysql命令加上選項-U後,當發出沒有WHERE或LIMIT關鍵字的UPDATE或DELETE時,MySQL程式就會拒絕執行。那麼,我們基於MySQL提供的這項設定,就可以輕鬆實現如何最大程度防止人為誤操作MySQL資料庫了。什麼?你不信?不信我們就從MySQL的幫助說明說起,一起來看看如何基於MySQL的-u選項實現如何最大程度防止人為誤操作MySQL資料庫。

MySQL幫助說明

[root@binghe~]# mysql --help|grep dummy      
 -U, --i-am-a-dummy Synonym for option --safe-updates, -U.
i-am-a-dummy      FALSE

在mysql命令加上選項-U後,當發出沒有WHERE或LIMIT關鍵字的UPDATE或DELETE時,MySQL程式就會拒絕執行。

指定-U登入測試

[root@binghe~]# mysql -uroot -proot -S /data/3306/mysql.sock -U
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.7.24-log MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> delete from oldboy.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> quit
Bye

提示:不加條件無法刪除,目的達到。

指定別名

我們可以將操作MySQL的命令做成別名,防止他人和DBA誤操作資料庫,將操作MySQL的命令做成別名也非常簡單,這裡,我們直接上示例了,如下所示。

[root@binghe~]# alias mysql='mysql -U'
[root@binghe~]# mysql -uroot -poldboy123 -S /data/3306/mysql.sock
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 5.7.24-log MySQL Community Server (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> delete from oldboy.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> delete from oldboy.student where Sno=5;
Query OK, 1 row affected (0.02 sec)
mysql> quit
Bye

在命令列會話設定alias mysql='mysql -U'之後,只能在當前會話有效,關閉當前連線伺服器的命令列之後,會話失效,則別名設定也會隨之失效。如果想關閉連線伺服器的會話終端,別名設定仍然有效,或者多個會話都能夠使用這個別名來操作資料庫,則我們可以將設定別名的命令新增到/etc/profile系統環境變數中,如下所示。

[root@binghe~]# echo "alias mysql='mysql -U'" >>/etc/profile
[root@binghe~]# . /etc/profile
[root@binghe~]# tail -1 /etc/profile
alias mysql='mysql -U'

這樣,當我們退出當前連線伺服器的會話終端,MySQL的別名設定依然有效,每次連線伺服器時,不必在當前會話中重新設定MySQL的命令別名,直接使用即可。

總結

在mysql命令加上選項-U後,當發出沒有WHERE或LIMIT關鍵字的UPDATE或DELETE時,MySQL程式拒絕執行。