Infolinks

Saturday, July 14, 2012

How to use Node.js with mysql


New to Node.js and want to know that how to use most famous open source database 'mysql' with it. Here i have a big surprise for you - it is surprisingly very easy to get MySQL working with Node.js. My this post will show you that how you can do it
So for use mysql with node.js first of all you need a node.js module mysql. To install mysql module just use following command using npm
$ npm install mysql


The mysql module is entirely written in Node.js, and implements an async MySQL client. The GitHub page of the project is located here , refer to it for other details about the API. Once you have installed the module, you can include it in your Node.js files and configure it this way.

var mycon = require('mysql'); 


var HOST = 'Your_MYSQL_HOST'; 
var PORT = Your_MYSQL_PORT; //Default 3306
var MYSQL_USER = 'Your_MYSQL_USER'; 
var MYSQL_PASS = 'Your_MYSQL_PASSWORD'; 
var DATABASE = 'Your_MYSQL_DATABASE';


var mysql = mycon.createClient({ 
            host: HOST, 
            port: PORT, 
            user: MYSQL_USER, 
            password: MYSQL_PASS, 
            });


mysql.query('use ' + DATABASE);


Now you can execute MySQL commands on the database.
Here is an example of mysql select query


mysql.query('select id,emp_name,emp_dep from TABLE_NAME where emp_salery > 300000',
function(err, result, fields) {
    if (err) throw err;
    else {
        console.log('Employees with salary greater than 300000 \n');
        for (var i in result) {
            var empdata = result[i];
            var empid = empdata.id;
            var emp_name = empdata.emp_name;
            var emp_dep = empdata.emp_dep;
            console.log("Emp ID : "+empid+"  Emp Name : "+emp_name+"  Emp Dep : "+emp_dep);
        }
    }
});


Now Here is an example of mysql insert query

mysql.query('insert into TABLE_NAME (emp_name, emp_dep, emp_salery) values ('XYZ', 'ABC', 500000)',
function selectCb(err, results, fields) {
    if (err) throw err;
    else 
    {
    console.log("Mysql Query Successfully Executed");
    }
});

Same process is used for mysql update query, Now To get the last insert ID, you use the insertid property of the insert result object.

client.query('INSERT INTO TABLE_NAME(column1, column2) values('a','b')', function(err, ress) {
    console.log(ress.insertId);
});


So above describe steps are used to use mysql with node.js. There are also many modules available for use mysql with node.js, but this is the best module which fulfill your requirements.

No comments:

Post a Comment