Tgwizman Tgwizman - 3 months ago 18
MySQL Question

How can I use MySQL with Node.js?

I've looked around for a bit, but I haven't found a way to use Node.js to access MySQL. How would I do that without using a side program?

Answer

The way to go is to

  • download node.js,
  • install mysql server (I had it bundled in wamp)
  • using node npm install mysql driver by felixge
  • connect to mysql from your server .js files

1 download and install node.js

2 Install mysql server (google it)

3 install mysql driver (node-mysql) using node package manager (npm comes with node)

   c:\your_node_server_folder\npm install mysql@2.0.0-alpha8

4 Now, in your server.js file put something like: var PORT = 1983; //Tyear of my birth ;) var restify = require('restify'); var db = require('./mysql_conn');

var options = { serverName: 'Lets meetapp node.js apis', accept: [ 'application/json' ] }

var PORT = 1983;
server.listen(PORT, '0.0.0.0');
console.log("listening "+PORT);
var db = require('./mysql_conn'); 

notice the last line. I am importing the file mysql_conn.js that has the following content:

//Require mysql connector that you installed with npm
var mysql      = require('mysql');

var conn_conf= {
    host     : 'localhost',
    port     :3306,
    user     : 'root',
    password : 'root',
    database: 'mydatabasename'
}

var connection = mysql.createConnection(conn_conf);

connection.connect(function(err) {
    if(err) console.log("Could not connect to DB");
    else{
        console.log("Connected to "+conn_conf.database+' on '+conn_conf.host );
    }
});

The code above will connecto to mysql db that is on the same machine listening the default 3306 port....

And finally a simple query:

connection.query( 'SELECT * FROM mydatabase.mytable ', function(err, rows) {
            console.log("SELECT * FROM mytable ");

            for(var i=0; i<rows.length; i++){
                console.log(rows[i]);
            }

            return rows;

    }

hope it helps!