MySQL - 创建用户,如果不是存在

时间:2016-02-14 14:09:46

标签: mysql

CREATE USER IF NOT EXISTS ...

创建一个没有问题的新用户。现有用户返回该错误,但文档读取CREATE USER for MySQL > 5.7.6支持该错误。

MySQL版本

Ver 14.14 Distrib 5.7.11, for osx10.9 (x86_64) using  EditLine wrapper

样品

<root:none> CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar';
--------------
CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar'
--------------

Query OK, 0 rows affected (0.00 sec)

<root:none> CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar';
--------------
CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar'
--------------

ERROR 1396 (HY000): Operation CREATE USER failed for 'foo'@'localhost'

建议?

2 个答案:

答案 0 :(得分:6)

如果您使用CREATE USER IF NOT EXISTS子句并且用户确实存在,则

IDENTIFIED BY会引发错误。如果您不使用IDENTIFIED BY子句,它不会抛出错误并按预期工作。

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar';
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar';
ERROR 1396 (HY000): Operation CREATE USER failed for 'foo'@'localhost'

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost';
Query OK, 0 rows affected, 1 warning (0.00 sec)

从5.7.8开始,您可以在使用CREATE USER IF NOT EXISTS子句调用DROP USER IF EXISTS之前使用CREATE USER,而不是使用IDENTIFIED BY

mysql> DROP USER 'foo'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> DROP USER 'foo'@'localhost';
ERROR 1396 (HY000): Operation DROP USER failed for 'foo'@'localhost'

mysql> DROP USER IF EXISTS 'foo'@'localhost';
Query OK, 0 rows affected, 1 warning (0.00 sec)

另一个选项是先创建用户,然后在创建用户后设置密码。

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SET PASSWORD FOR 'foo'@'localhost' = 'bar';
Query OK, 0 rows affected (0.01 sec)

答案 1 :(得分:-1)

尝试执行FLUSH特权。

FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'foo'@'localhost';

您可以查看链接。它可能对你有帮助

link