这是 index.js 代码:**** var db_sql = require(‘./mysql_db’); console.log(db_sql.Select_byName(‘Tom’)); 这是 mysql_db.js代码:
var mysql = require('mysql');
var conn =mysql.createConnection({
host:'localhost',
user: 'root',
password:null,
database:'nodejs',
port:3306
});
var sql;
exports.Delete_ByName = function(name){
sql ="delete from User where UserName = '"+name+"'";
Query();
}
exports.Update_ByName = function(name,val){
sql = "update User set UserName ='"+val+"' where Username='"+name+"' ";
Query();
}
exports.Select_byName = function(name){
sql = "select * from User where UserName ='"+name+"'";
return Query();
}
exports.Insert_Date = function(val){
sql = "insert into User values("+val+")";
Query();
}
function Query(){
conn.connect();
conn.query(sql,function(err,results){
if (err) {
throw err;
};
});
conn.end(function(err){
if (err) {
throw err;
};
console.log('mysql close');
});
} 问题来了,Select_byName这个返回值results怎么得到?
10 回复
一般不带这样层层嵌套的,如果你一定要这样写的话,就加个callback,
exports.Select_byName = function(name, callback){
sql = "select * from User where UserName ='"+name+"'";
return Query(callback);
}
function Query(callback){//加callcack
conn.connect();
conn.query(sql,callback);
conn.end(function(err){
if (err) {
throw err;
};
console.log('mysql close');
});
调用的时候就db_sql.Select_byName(‘Tom’, function(err, results){ console.log(results)})