ADVERTISEMENT
ADVERTISEMENT

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

//step-1
var mysql = require('mysql');
//step-2
var con = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "123"
});
//step-3
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
//step-4
  var sql = "CREATE DATABASE demo";
//step-5
  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 127.0.0.1 instead of localhost.

Thank you!

ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.