[解决] Error Code: 1044. Access denied for user 'root'@'%' to database
一、创建数据库用户
命令:CREATE USER 'username'@'host' IDENTIFIED BY 'password';
说明:
username:你将创建的用户名
host:指定该用户在哪个主机上可以登陆,如果是本地用户可用localhost,如果想让该用户可以从任意远程主机登陆,可以使用通配符%
password:该用户的登陆密码,密码可以为空,如果为空则该用户可以不需要密码登陆服务器
例子:
CREATE USER 'username'@'host' IDENTIFIED BY 'password'; CREATE USER 'dog'@'localhost' IDENTIFIED BY '123456'; CREATE USER 'pig'@'192.168.1.101_' IDENDIFIED BY '123456'; CREATE USER 'pig'@'%' IDENTIFIED BY '123456'; CREATE USER 'pig'@'%' IDENTIFIED BY ''; CREATE USER 'pig'@'%';
二. 授权:
命令:GRANT privileges ON databasename.tablename TO 'username'@'host'
说明:
privileges:用户的操作权限,如SELECT,INSERT,UPDATE等,如果要授予所的权限则使用ALL
databasename:数据库名
tablename:表名,如果要授予该用户对所有数据库和表的相应操作权限则可用*表示,如*.*
例子:
GRANT SELECT, INSERT ON test.user TO 'pig'@'%';
GRANT ALL ON *.* TO 'pig'@'%';
GRANT ALL ON maindataplus.* TO 'pig'@'%';
注意:
用以上命令授权的用户不能给其它用户授权,如果想让该用户可以授权,用以下命令:
GRANT privileges ON databasename.tablename TO 'username'@'host' WITH GRANT OPTION;
我是以root用户登录mysql的,怎么还会遇到这问题呢,有点猫腻,我查看了下mysql下user表的各用户的权限信息
MariaDB [(none)]> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user; +-----------+--------------+-------------------------------------------+------------+------------+ | host | user | password | Grant_priv | Super_priv | +-----------+--------------+-------------------------------------------+------------+------------+ | localhost | root | *0B42D92AC77455330A27220D61D24E3BC5740CCF | N | N | | 127.0.0.1 | root | *0B42D92AC77455330A27220D61D24E3BC5740CCF | Y | Y | | ::1 | root | *0B42D92AC77455330A27220D61D24E3BC5740CCF | Y | Y | | % | root | *0B42D92AC77455330A27220D61D24E3BC5740CCF | Y | Y | | % | cloudcon-api | *6A10AB79A4E1F6E732940B18612AF3C7A1F1528E | Y | Y | | localhost | cloudcon | *5C16B0FAA9461AFF9D78785B71A86ECD0D1583D2 | Y | Y | +-----------+--------------+-------------------------------------------+------------+------------+ 6 rows in set (0.00 sec)
可以看到授权的权限没有打开: Grant_priv is set to N for root@%. 修复下
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root'; FLUSH PRIVILEGES;
重新登录下,就ok了。如果不能执行update的话,那就先停下mysql服务,然后mysqld_safe --skip-grant-table &