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-alpha7Code language: CSS (css)

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',
});Code language: JavaScript (javascript)

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);
	   } 
  }
});Code language: JavaScript (javascript)

Leave a Reply

Your email address will not be published. Required fields are marked *