Create a MySQL Database and User
This guide covers creating a MySQL database, creating a dedicated user, and granting the appropriate privileges. It covers both MySQL 5.x (implicit GRANT-based user creation) and MySQL 8+ (explicit CREATE USER required).
Prerequisites
- MySQL server installed and running
- Access to the MySQL root account or an account with GRANT privileges
Steps
1. Log in to MySQL as root:
mysql -u root -p
2. Create the database with UTF-8 character set:
CREATE DATABASE myappdb DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
3a. MySQL 5.x — create user and grant privileges in one step:
GRANT ALL PRIVILEGES ON myappdb.* TO 'myappuser'@'localhost' IDENTIFIED BY 'StrongPassword123';
FLUSH PRIVILEGES;
3b. MySQL 8+ — create user first, then grant:
CREATE USER 'myappuser'@'localhost' IDENTIFIED BY 'StrongPassword123';
GRANT ALL PRIVILEGES ON myappdb.* TO 'myappuser'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
To allow access from any host instead of localhost, replace 'myappuser'@'localhost' with 'myappuser'@'%'.
Verify
SHOW DATABASES;
SELECT User, Host FROM mysql.user WHERE User = 'myappuser';
SHOW GRANTS FOR 'myappuser'@'localhost';
Notes
- In MySQL 8+,
GRANT ... IDENTIFIED BYis no longer supported — always useCREATE USERfirst. - If a user exists but cannot authenticate, check the authentication plugin:
SELECT User, plugin FROM mysql.user;and update withALTER USERif needed.