Node.js connect MySQL example
Node.js中連線MySQL相當方便(相信連線其他資料庫也差不多吧!)
這邊以三個步驟介紹撰寫MySQL撈資料的standalone程式
步驟如下:
步驟1. node mysql package
npm install mysql
步驟2. db configure
$ vi mysql-config.js
var db_options = {
host: 'your.database.address',
port: your_database_port,
user: 'access_database_name',
password: 'access_database_password',
database: 'database_that_will_be_use'
};
var mysql = new require('mysql'), db = null;
if(mysql.createClient) {
db = mysql.createClient(db_options);
} else {
db = new mysql.Client(db_options);
db.connect(function(err) {
if(err) {
console.error('connect db ' + db.host + ' error: ' + err);
process.exit();
}
});
}
exports.db = db;
步驟3. simple query
$ vi mysql-example.js
var config = require('./mysql-config')
, db = config.db;
exports.doit = function() {
//Query
db.query('SELECT * FROM SOME_TABLE', function(err, rows, fiels) {
if(err) return next(err);
console.log(rows); //This can show the queried result rows.
console.log(fiels); //This can show the query result fields
db.end(); //End of connection
});
}
//Start point
this.doit();