How to connect MySql database with Nodejs

Nodejs is a powerful platform which used for real-time data with flexible of handling data in file system or database side.  Today tutorial we are going to discuss about the connecting MySql with Nodejs.

Before getting into our code part, first will discuss about things needed for MySql connecting with Nodejs then will move to our code side.

First we need to check the MySql package is installed in our current Nodejs version or not. We have the command to check list or individual package installed in Nodejs. If the package is installed it will display the package else show “(empty)” value.

Display list of packages

Nodejs npm list command

Nodejs npm list command

Nodejs npm list packages

Nodejs npm list packages

Let’s see how to execute individual package and their output display.

Nodejs npm list mysql command

Nodejs npm list mysql command

Now we will see our code part with line by line.

// include mysql package
var mysql = require('mysql');

//setting up the database in config variable 
var mysqlConfig = {host:'localhost',user:'root',password:'',database:'my_database'}

//Creating mysql connection in conn
var conn = mysql.createConnection(mysqlConfig);


//Writing a simple query, which will display id,name from the user table
var sql = 'SELECT id,name FROM user';


//Fetching the data from the table, if error occurs it will display the error else display the data.
conn.query(sql,function(err, rows, fields) {	
	if (err) {

		console.log(err);
	}
	for(i in rows) 
	{
		console.log(rows[i].id+"="+rows[i].name+"\n");
	}
});


//closing the connection
conn.end();

Once you have created mysql_data.js file, execute in Nodejs.

Nodejs execute mysql_data

Nodejs execute mysql_data

Output will display like below format, rows will be in next line in the terminal.

Nodejs output mysql_data

Nodejs output mysql_data

If the error occurs in database connection or query, it will throw error message in the terminal.

Nodejs error occurs invalid sql

Nodejs error occurs invalid sql

 

Share