Home » Node.js

Create MYSQL database by using Node.js

In this article, we are going to learn how to create a database in MySQL in Node.js?
Submitted by Manu Jemini, on November 20, 2017

Database connectivity is an important part of each and every project so, in this article we are going to learn how to connect our node server Mysql server and create a database for a schema.

Before creating connection we need to require mysql module and keep its reference in a local variable and after that, we establish a connection by using .createConnection() method and initialize host, username, and password of our database.

Now we are all set with connection and all we need to invoke .connect() method with a callback in which, first we print a message that shows we are successfully connected and then create a query string to create a database. After that, by using .query() we execute our query and in the callback function, we manage a condition to throw an error if any and shows a message that "Database created".

Database details:

  • Hostname: localhost
  • Port number: 3306
  • Username: root
  • Password: 123

Server File

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "",
  user: "root",
  password: "123"
con.connect(function(err) {
  if (err) throw err;
  var sql = "CREATE DATABASE demo";
  con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("Database created");

Discussing above steps:

  • Require module mysql.
  • Creating Connection variable using .createConnection() method.
  • Connect by using .connect() method.
  • Creating SQL query.
  • Execute query by using .query() method.
Node.js - create a MySQL database

create a MySQL database in Node.js

Note: Use instead of localhost.

Thank you!

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.