MySQL 賦予用戶權限命令的簡單格式可概括為:
grant 權限 on 數據庫對象 to 用戶
用戶后面可以加@'ip地址' identified by '密碼'
例如:
grant all on *.* to root@'%'IDENTIFIED by '123456'
grant all on *.* to ted@'192.168.1.51' IDENTIFIED by '123456'
上面的語句表示將 所有 數據庫的所有權限授權給 ted 這個用戶,允許 ted 用戶在 123.123.123.123 這個 IP 進行遠程登陸,並設置 ted 用戶的密碼為 123456 。
下面逐一分析所有的參數:
USAGE:連接(登錄)權限,建立一個用戶,就會自動授予其usage權限(默認授予)。該權限只能用於數據庫登錄,不能執行任何操作,且該權限不能被回收,即使使用REVOKE也不能刪除用戶權限。
all PRIVILEGES 表示賦予所有的權限給指定用戶,這里也可以替換為賦予某一具體的權限,例如:select,insert,update,delete,create,drop 等,具體權限間用“,”半角逗號分隔。 discuz.* 表示上面的權限是針對於哪個表的,discuz 指的是數據庫,后面的 * 表示對於所有的表,由此可以推理出:對於全部數據庫的全部 表授權為“*.*”,對於某一數據庫的全部表授權為“數據庫名.*”,對於某一數據庫的某一表授權為“數據庫名.表名”。 ted 表示你要給哪個用戶授權,這個用戶可以是存在的用戶,也可以是不存在的用戶。 123.123.123.123 表示允許遠程連接的 IP 地址,如果想不限制鏈接的 IP 則設置為“%”即可。 123456 為用戶的密碼。 執行了上面的語句后,再執行下面的語句,方可立即生效。 > flush privileges;
一、grant 普通數據用戶,查詢、插入、更新、刪除 數據庫中所有表數據的權利
grant select, insert, update, delete on testdb.* to common_user@'%'
二、grant 數據庫開發人員,創建表、索引、視圖、存儲過程、函數等權限
grant 創建、修改、刪除 MySQL 數據表結構權限。
grant create,alter,drop on testdb.* to developer@'192.168.0.%';
三、grant 操作 MySQL 外鍵權限:
grant references on testdb.* to developer@'192.168.0.%';
四、grant 操作 MySQL 臨時表權限:
grant create temporary tables on testdb.* to developer@'192.168.0.%';
五、grant 操作 MySQL 索引權限:
grant index on testdb.* to developer@'192.168.0.%';
六、grant 操作 MySQL 視圖、查看視圖源代碼權限:
grant create view,show vuew on testdb.* to developer@'192.168.0.%';
七、grant 操作 MySQL 存儲過程、函數權限:
grant create routine on testdb.* to developer@'192.168.0.%'; -- now, can show procedure status grant alter routine on testdb.* to developer@'192.168.0.%'; -- now, you can drop a procedure grant execute on testdb.* to developer@'192.168.0.%';
八、grant 普通 DBA 管理某個 MySQL 數據庫的權限
grant all privileges on testdb to dba@'localhost'
其中,關鍵字 “privileges” 可以省略。
九、grant 高級 DBA 管理 MySQL 中所有數據庫的權限:
grant all on *.* to dba@'localhost'
十. grant 作用在表中的列上:
grant select(id, se, rank) on testdb.apache_log to dba@localhost;
十一、查看 MySQL 用戶權限
查看當前用戶(自己)權限:
show grants;
查看其他 MySQL 用戶權限:
show grants for 'wuzhd';
十二、撤銷已經賦予給 MySQL 用戶權限的權限。
(1) revoke 跟 grant 的語法差不多,只需要把關鍵字 “to” 換成 “from” 即可:
grant all on *.* to dba@localhost; revoke all on *.* from dba@localhost;
(2) MySQL grant、revoke 用戶權限注意事項
(3) grant, revoke 用戶權限后,該用戶只有重新連接 MySQL 數據庫,權限才能生效。
(4) 如果想讓授權的用戶,也可以將這些權限 grant 給其他用戶,需要選項 “grant option“
grant select on testdb.* to dba@localhost with grant option;