nodejs同步操作mysql

// db-util.js
var mysql = require('mysql');
var pool = mysql.createPool({
  connectionLimit : 10,
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test',
  port: 3306
});

exports.dataCenter = function(sql, fn) {
  // (callback && typeof(callback) === "function")
  pool.getConnection(function (err, conn) {
    if (err) {
      console.log("POOL ==> " + err);
      return fn(err);
    } else {
      conn.query(sql, function (err, res) {
        conn.release();
        return fn(res);
      });
    }
  });
};
// 利用回调函数达到同步操作数据并获取信息的效果
var mysql = require('mysql')
  , dbUtil = require('./db-util');

var selectSQL = "select * from ?? where idcard = ?";
var selectArr = ['employee', 'xxxxx'];
selectSQL = mysql.format(selectSQL, selectArr);

dbUtil.dataCenter(selectSQL, function(data) {
  console.log(data);
});
[ { id: 1,
    name: 'Happy',
    idcard: 'xxxxx',
    department: 'frontend',
    birthday: Sat Oct 07 1989 00:00:00 GMT+0800 (中国标准时间), 
    salary: 1234.56,
    create_date: Wed Oct 29 2014 14:03:08 GMT+0800 (中国标准时间) 
  }...]

相关推荐