common.js:
----------------------------------------
var db = {};
var mysql = require('mysql');
db.query = function(pool, sql, callback){
if (!sql) {
callback();
return;
}
pool.query (sql, function(err, rows, fields) {
if (err) {
console.log(err);
callback(err, null);
return;
};
callback(null, rows, fields);
});
}
module.exports = db;
test.js调用:
----------------------------------------
var db = require('../common/dbcom');
var mysql = require('mysql');
var pool = mysql.createPool({
host : '192.168.1.xx',
database : 'xxx',
user : 'xx',
password : 'xx',
port : '3306',
multipleStatements:true
});
var sql1 = 'SELECT count(*) as count from student';
db.query (pool,sql1, function(err, rows, fields){
if (err) {
console.log(err);
return;
}
console.log('sql1:', rows[0].count);
});
var sql2 = "update student set age='22' where id=2;\
update student set age='21'"
db.query (pool,sql2, function(err, rows, fields){
if (err) {
console.log(err);
return;
}
console.log('sql2-1:', rows[0].affectedRows);
console.log('sql2-2:', rows[1].affectedRows);
});
运行结果:
----------------------------------------
Debugger listening on ws://127.0.0.1:42098/8ad43bdd-0d34-4bb1-98ef-6a3fa30e7e84
For help, see: https://nodejs.org/en/docs/inspector
sql1: 7
test.js:18
sql2-1: 1
test.js:28
sql2-2: 7