Database Connection Using Node.js and MYSQL

From this article you will get to know how to create a database connection in Node.js.



Before creating the database connection you should have installed MYSQL on your computer.
Go to your project folder and create a file called connection .js. Then copy the following code into it.

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: ""
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected successfully!");
  con.query("CREATE DATABASE nodedb", function (err, result) {
    if (err) throw err;
    console.log("Database is successfully created");
  });
});

Here the database which is known as nodedb will be created in the code itself. If there is no any error it will gives the output of 

"Connected successfully!"
" Database is successfully Created "

 if not command line will display the error.

Now run the file in the project.Hope to see you soon with more articles on Node.js.




Comments