I've just started getting into Node.js. I come from a PHP background, so I'm fairly used to using MySQL for all my database needs.
How can I use MySQL with Node.js?
Answers
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'
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.
You can also try out a newer effort known as Node.js DB that aims to provide a common framework for several database engines. It is built with C++ so performance is guaranteed.
Specifically you could use its db-mysql driver for Node.js MySQL support.
connect the mysql database by installing a library. here, picked the stable and easy to use node-mysql module.
npm install mysql@2.0.0-alpha2
var http = require('http'),
mysql = require('mysql');
var sqlInfo = {
host: 'localhost',
user: 'root',
password: 'urpass',
database: 'dbname'
}
client = mysql.createConnection(sqlInfo);
client.connect();
0 comments:
Post a Comment