Skip to content

Instantly share code, notes, and snippets.

@ETiV
Last active May 19, 2016 17:18
Show Gist options
  • Save ETiV/9932144 to your computer and use it in GitHub Desktop.
Save ETiV/9932144 to your computer and use it in GitHub Desktop.
Node.JS mysql 数据库快速访问
/**
* Created by ETiV on 10/24/14.
*/
var mysql = require('mysql')
, config = require('./config');
/**
* config =
* {
mysql: {
host: '127.0.0.1',
port: 3306,
user: 'Username',
password: 'Password',
database: 'Database'
}
* }
**/
var pool, singleton_db_pool_key = '_MYSQL_DATABASE_POOL_';
if (process[singleton_db_pool_key] == undefined) {
pool = process[singleton_db_pool_key] = mysql.createPool(config.mysql);
} else {
pool = process[singleton_db_pool_key];
}
module.exports = {
escape: mysql.escape,
escapeId: mysql.escapeId,
query: function (sql, values, cb) {
if (typeof values === 'function') {
cb = values;
values = undefined;
} else if (typeof cb !== 'function') {
cb = function () {
};
}
return pool.query(sql, values, function (errQuery, results) {
cb(errQuery, results);
});
},
end: function (cb) {
pool.end(cb);
},
now: function(){return ~~(Date.now() / 1000);}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment