Node.js MySQL Create Database

Hi Guys,

we will see Node.js MySQL Create Database. For any kind of data store or run query then we need databases like MySQL, MongoDB, PostgreSQL but one of the most popular databases is MySQL.

we can create a database in MySQL using Node.js in using MySQL module or connect MySQL with node.js.

You can download MySQL database: https://www.mysql.com/downloads/.

Step 1: Install MySQL Driver

First, you have to need MySQL and running on your computer, you can access it by using Node.js.

To access a MySQL database with Node.js, you need a MySQL driver. now we will use the “MySQL” module, downloaded from NPM.

To download and install the “MySQL” module in an application using the below command.

npm install mysql

Now you have downloaded and installed a Mysql database driver.

Node.js can use this module to manipulate the MySQL database :

var mysql = require('mysql');

Step 2: Connect Database

Create a db_connection.js file for your application. and copy the below code in that file.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "your_username",
  password: "your_password"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected..!!");
});

Step 3: Create Database with Connection

Create a database in MySQL, use the “CREATE DATABASE” statement. So, copy the below code and paste it into your file.

Database Name : node_mysql_demo

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "your_username",
  password: "your_password"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected..!!");
  con.query("CREATE DATABASE node_mysql_demo", function (err, result) {
    if (err) throw err;
    console.log("Database Created..!!");
  });
});

Step 4: Run db_connection.js file

run db_connection.js using the below code :

node db_connection.js

You May Also Like

About the Author: Sumanta Kabiraj

Leave a Reply

Your email address will not be published. Required fields are marked *