通過create user 命令來創建用戶, 有兩種方式:(只介紹通過 create user 命令, 直接往user表中插入數據的方式,這里就不說了)
創建用戶的同時, 指定用戶可登錄的主機和密碼
create user 'test_user'@'%' identified by "123";
create user 'test_user'@'localhost' identified by "123";
create user 'test_user'@'127.0.0.1' identified by "123";
grant all privileges on test_db.* to 'test_user'@'%';
grant select,update,delete,insert,drop on test_db.* to 'test_user'@'%';
grant all privileges on test_db.* to 'test_user'@'%' identified by '1112';
grant all privileges on test_db.* to 'test_user'@'%' with grant option;
首先解釋一下創建用戶的命令參數:
'test_user'
是用戶名@
后面是指定的登錄主機,'localhost'
和'127.0.0.1'
表示只能在 本地登錄;'%'表示只能在遠程主機登錄identified by
后面是密碼- 友情提示: 上述命令中,用戶名, 登錄主機, 密碼, 建議都使用 引號包起來, 防止不必要的麻煩
分配權限的命令參數:
grant
是分配權限的命令all privileges
指所有的權限, 也可以像第二條那樣, 指定某些權限給用戶test_db.*
表示 test_db庫的所有表, 可以指定某個表test_db.table1
, 或者所有數據庫的所有表,*.*
identified by
指定密碼, 如果不指定, 默認用創建用戶的時候的密碼, 或者可以不同的權限,給不同的密碼, 或者不同的登錄主機給不同的密碼, 都是可以的with grant option
如果帶着這個參數, 表示這個被分配權限的用戶, 還可以把自己的權限分配給其他人- 用grant語句創建權限是不需要再手工刷新授權表的,因為它已經自動刷新了。
上面前三條命令只能同時使用一條, 因為create user 不能創建同名的用戶
那么問題就來了, 假設通過第一條命令創建了用戶, 那么這個用戶就只能在遠程主機上登錄, 而不能在本地登錄, 如果在本地登錄, 會報這個錯誤:ERROR 1045 (28000): Access denied for user 'card_test1'@'localhost' (using password: YES)
出現這個錯誤有很多種情況, 據我的了解, 可能是:
- 用戶沒有在本地登錄的權限, 也就是
'card_test1'@'localhost'
這個用戶不存在, 因為只存在'card_test1'@'%'
這個用戶 - 密碼不對
為了解決這個問題, 可以通過第二種方式, 也就是create user 的時候, 不分配登錄主機這些參數
只創建用戶, 不分配主機
1. create user test_user;
2. create user test_user identified by "123";
3. grant all privileges on test_db.* to 'test_user'@'%' identified by "1234";
4. grant all privileges on test_db.* to 'test_user'@'localhost'identified by "1235";
上面的命令, 1,2 執行一條, 單純的創建用戶, 或者同時分配密碼;
然后, 3,4 兩條都可以執行, 這樣就能讓test_user 這個用戶, 既能在本地登錄, 又能在遠程登錄, 如果 grant的時候, 設置不同的密碼, 還能使在不同主機登錄的同一個用戶, 使用不同的密碼
取消用戶權限
使用 revoke
語句
revoke all on test_db.* from 'test_user'@'localhost';
這個命令就取消了 test_user 這個用戶, 在本地登錄時的全部權限
刪除用戶
drop user 'test_user'@'%';
drop user 'test_user'@'localhost';
修改指定用戶的密碼
update mysql.user set password=password('new_passwd') where User='test_user' and Host='%';
創建用戶給用戶創建權限或者修改權限, 都可以通過直接操作 mysql.user表; 注意直接操作表的話, 需要用
flush privileges;
命令 刷新權限