Node.js与mysql查询同步

时间:2018-04-13 07:54:19

标签: mysql node.js synchronous

我正在尝试使用node.js在mysql中实现同步查询,我尝试了几种方法并且没有成功

我是node.js的新手

我使用express.js

connection.js

var mysql = require('mysql');

var connMySql = function() {
    return mysql.createConnection({
            host : 'localhost',
            user : 'root',
            password : '******', 
            database : 'ress'
        });

}

module.exports = function() {
    return connMySql;

} 

DAO.js

function UserDAO(connection){

    this._connection = connection(); 
}


UserDAO.prototype.createUser = function (user, callback){

    var sql = "insert into... ";

    this._connection.query(sql, function(err, result){
        //console.log(result)
        //console.log()
        if (err){
            callback(err,false )

        }
        if (result){

            var newI = result.insertId

            var sqlOther = "insert into ..... ";

            this._connection.query(sql, function(err, result){
                if (err){
                    callback(err,false )
                }else if (result.length > 0){


                    callback(false, result.insertId)
                }
            }); 


        }
    }); 
}

我尝试实现await,async和Promisse(.then)但没有成功。

我需要同步调用并返回插入ID?

感谢

2 个答案:

答案 0 :(得分:0)

从mysql repo我发现你缺少connection.connect()

答案 1 :(得分:0)

<强> connection.js

var mysql = require('mysql');
var connection = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '******', 
    database : 'ress'
});

connection.connect(function(err) {
    if (err) throw err;
});

module.exports = connection;

DAO _connection在完成工作后必须关闭

UserDAO.prototype.createUser = function (user, callback){
    var sql = "insert into... ";
    this._connection.query(sql, function(err, result){
        //console.log(result)
        //console.log()
        if (err){
            callback(err,false )
            this._connection.end();
        }
        if (result){
            var newI = result.insertId
            var sqlOther = "insert into ..... ";
            this._connection.query(sql, function(err, result){
                if (err){
                    callback(err,false )
                } else if (result.length > 0){
                    callback(false, result.insertId)
                }
                this._connection.end();
            }); 
        }
    }); 
}