Last Updated: February 25, 2016
·
4.271K
· markushausammann

mysql - create user if not exists?

Unfortunately there isn't such a thing, so if you try to create a user that already exists you'll get an error. But there is a nice workaround.

GRANT ALL PRIVILEGES ON `database`.* TO 'user'@'localhost';

...will do exactly that. If the user exists, the privileges will be granted, if the user doesn't exist, it will be created first.

Watch out for sql-mode in your mysql configuration. In order for this to work, the setting must not contain NO_AUTO_CREATE_USER.

Example:

sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"