????4. ???1
????????????????????????????????????????????????? function ???????????
// connect.js ?????????????
var mysql = require('mysql');
var config = require('./config.json'); // ??????????????д??mysql??????config.mysql
var connCount = 0; // ?????δ????????
exports.getConn = function(){
connCount ++;
console.log('............................OPEN a connection?? has '+ connCount + ' connection.');
return mysql.createConnection(config.mysql);
};
exports.endConn = function(conn){
conn.end(function(err){
if(!err){
connCount --;
console.log('.........................CLOSE a connection?? has '+ connCount + ' connection.');
}
});
};
????????????????????????
// db.js ?????????
var connect = require('./connect.js'); // ???????????????
exports.getUser = function(username?? callback){
var connection = connect.getConn();
var sql = 'select * from user where username = "' + username + '"';
connection.query(sql??function(err??rows??fields){
callback(err??rows??fields);
});
connect.endConn(connection);
}
????5. ???2
??????????????????????????????????????????????????????
// connect.js ??????
var mysql = require('mysql');
var config = require('./config.json');
var pool = mysql.createPool(config.mysql);
exports.querySQL = function(sql??callback){
pool.query(sql?? function(err??rows??fields){
callback(err??rows??fields);
});
}
// connect.js ???getConnection????
var mysql = require('mysql');
var config = require('./config.json');
var pool = mysql.createPool(config.mysql);
exports.querySQL = function(sql?? callback){
pool.getConnection(function(err??conn){
conn.query(sql??function(err??rows??fields){
callback(err??rows??fields);
conn.release();   // ??????????
});
});
}
????????????????? querySQL ????????????£?
// db.js ?????????
var connect = require('./connect.js');
exports.getUser = function(username??callback){
var sql = 'select * from user where username = "' + username + '"';
connect.querySQL(sql??function(err??rows??fields){
callback(err??rows??fields);
});
};
?????????????????????????????????????????????? pool.query() ??????? pool.getConnection() ???????????????????н???????????????????????ò??????????????ж????????????о?????????????????л??~