How to connect to MySQL using Node.js

If you want to use MySQL with your Node.js app here's how to do it:

Install the MySQL

First of all go to https://npmjs.org/package/mysql to check the latest version. At the day of this post:

npm install mysql@2.0.0-alpha7

Connect to the MySQL

Now add the following lines somewhere at the top of your application:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
 // port 	   : '3308',
  database : 'my_dataase',
  user     : 'my_user',
  password : 'my_password',
});

Run a query

Use the following function to run a query. Notice the callback function you can use to retrieve rows, fields and errors.

I've used a for to go through all the returned results.

connection.query('SELECT * from my_table', function(err, rows, fields) {
  if (err){  console.log(err); }
  else{		  
  	console.log('************** Results **************');  	
	   for (var i = 0; i < rows.length; i++){
		   console.log(rows[i].MyField);
	   } 
  }
});

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*