Node.js MySQL Create Database

🚀 Node.js MySQL – Create Database

To create a database from Node.js, you must first connect to MySQL without specifying a database, then run a SQL command.

We’ll use mysql2 (recommended).


1. Install mysql2 Package

npm install mysql2

2. Create a MySQL Connection (No DB Selected)



 


3. Create a Database Using Node.js

create_database.js


 


4. Run the File

node create_database.js

📝 Output Example

MySQL Connected!
Database 'mydb' created successfully

⚡ Optional: Check if Database Exists Before Creating



 


⚠️ Important Notes

  • Use root or a user with database creation permissions.

  • Do not specify database: in connection config when creating a database.

  • Use IF NOT EXISTS to avoid errors if DB already exists.

You may also like...