Tgwizman
Tgwizman

Reputation: 1538

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?

Upvotes: 1

Views: 2617

Answers (3)

chovy
chovy

Reputation: 75844

Search http://search.npmjs.org/ (broken link) for mysql (there are several)

Upvotes: 2

Tgwizman
Tgwizman

Reputation: 1538

Looking back at this, I really should have simply went this route in the first place. Here's a little lib that I wrote for Node that is really, realy, realy helpful!

var fs = require('fs');
exports.saveJsonToFile = function(filePath, json) {
    fs.writeFileSync(filePath+'.json', JSON.stringify(json, null, " ")
}
exports.readJsonFromFile = function(filePath) {
    return JSON.parse(fs.readFileSync(filePath+'.json'))
}

Just save this to a file, then load the file to your project using:

var JsonFs = require('./Path/To/File');

players = JsonFs.readJsonFromFile('players');

JsonFs.saveJsonToFile('players', players);

PLEASE NOTE: JSON files don't support functions!!!

Upvotes: -1

luigi7up
luigi7up

Reputation: 5962

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 [email protected]

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!

Upvotes: 5

Related Questions