How to Connect Node.js with MySQL

Channel: Linux
Abstract: NPM and MySQL installed on your system. We will help you to install Node.js MySQL driver module on your system and a sample program to connect to MySQ

Node.js is an popular programming language like PHP & JAVA for web applications. Also MySQL is most popular database used for storing values. MySQL database driver for Node.js is available under NPM repository. In this tutorial we are assuming that you already have Node.js, NPM and MySQL installed on your system. We will help you to install Node.js MySQL driver module on your system and a sample program to connect to MySQL using node.js.

Step 1 – Install Node.js MySQL Module

MySQL driver for node.js is available under node package manager (NPM). Use the following command to install node.js MySQL driver on your system.

$ sudo npm install mysql
Step 2 – Sample Node.js Program

Below is sample node.js program which will connection node.js application with MySQL server. It will show success and error messages according to connections results and close the connection at the end of program. Create a JavaScript file app.js.

$ cd myApp
$ vim app.js

and add the following content to above file.

var mysql  = require('mysql');
var dbconn = mysql.createConnection({
  host     : 'localhost',
  user     : '<DB_USER>',
  password : '<DB_PASSWORD',
  database : '<DB_NAME>'
});

dbconn.connect(function(err){
  if(err){
    console.log('Database connection error');
  }else{
    console.log('Database connection successful');
  }
});

dbconn.end(function(err) {
  // Function to close database connection
});

Step 3 – Verify Connection

Now execute node.js script using command line and make sure Node.js is properly connecting with MySQL.

$ node app.js

Database connection successful

Ref From: tecadmin

Related articles