
Mysql Create Database in NodeJs
Creating a MySQL database in Node.js is super easy using the mysql
or mysql2
packages.
Let me show you how to do it step by step 👇
✅ Step 1: Install MySQL Package
Use either mysql
or mysql2
. We'll go with mysql
here:
npm install mysql
(If you want async/await support, use mysql2
instead.)
🛠️ Step 2: Create the Database
const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '' // 🔒 Replace with your actual password});connection.connect((err) => { if (err) throw err; console.log('Connected to MySQL!'); // Create database connection.query('CREATE DATABASE myDatabase', (err, result) => { if (err) throw err; console.log('Database created!'); connection.end(); // Close the connection });});
🧠 Notes:
If the DB already exists, you'll get an error. You can use:
CREATE DATABASE IF NOT EXISTS myDatabase
Replace
root
andpassword
with your actual MySQL credentials.If you use XAMPP, your host is usually
localhost
and password is empty by default.
🔄 Want to use mysql2
with async/await?
npm install mysql2
const mysql = require('mysql2/promise');async function createDB() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: '' }); await connection.query('CREATE DATABASE IF NOT EXISTS myDatabase'); console.log('Database created!'); await connection.end();}createDB();
Let me know if you want to:
Create tables after this
Connect to the database
Insert or query data