MySQL with Node.js
Since this is an old thread just adding an update:
To install the MySQL node.js driver:
If you run just npm install mysql
, you need to be in the same directory that your run your server. I would advise to do it as in one of the following examples:
For global installation:
npm install -g mysql
For local installation:
1- Add it to your package.json
in the dependencies:
"dependencies": {
"mysql": "~2.3.2",
...
2- run npm install
Note that for connections to happen you will also need to be running the mysql server (which is node independent)
To install MySQL server:
There are a bunch of tutorials out there that explain this, and it is a bit dependent on operative system. Just go to google and search for how to install mysql server [Ubuntu|MacOSX|Windows]
. But in a sentence: you have to go to http://www.mysql.com/downloads/ and install it.
Check out the node.js module list
- node-mysql — A node.js module implementing the MySQL protocol
- node-mysql2 — Yet another pure JS async driver. Pipelining, prepared statements.
- node-mysql-libmysqlclient — MySQL asynchronous bindings based on libmysqlclient
node-mysql looks simple enough:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
});
Queries:
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
// Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
node-mysql is probably one of the best modules out there used for working with MySQL database which is actively maintained and well documented.