Node.js MySQL: Create Database
Creating a MySQL database from a Node.js application is a common task. This tutorial shows you how to do it using the mysql package and the SQL CREATE DATABASE statement.
Node.js Tutorial:-
SQL Tutorial:-
Install the MySQL Package
npm install mysql
Example: Create updategadh Database
Create a file named updategadh.js inside a folder called DBexample:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE updategadh", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
Run the Script
node updategadh.js
// Expected:
// Connected!
// Database created
Verify in MySQL
SHOW DATABASES;
-- updategadh should appear in the list
Safer: CREATE DATABASE IF NOT EXISTS
con.query("CREATE DATABASE IF NOT EXISTS updategadh", function (err) {
if (err) throw err;
console.log("Database ready");
});
This avoids an error if the database already exists.
Download New Real Time Projects:- Click here
Complete Advance AI topics:-
Conclusion
Creating a MySQL database from Node.js takes only a connection and a single query. Use IF NOT EXISTS for idempotent scripts. For more tutorials, stay tuned to .
node js mysql create database example
node js mysql create database w3schools
node js mysql connection
connect mysql with node js express
create database javascript
nodejs mysql database tutorial
nodejs mysql crud
nodejs mysql2