node.js与mysql查询同步

cnjp1d6j  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(411)

我正在尝试用node.js在mysql中实现一个同步查询,我尝试了几种方法,但都没有成功
我是node.js的新手
我使用express.js
连接.js

var mysql = require('mysql');

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

}

module.exports = function() {
    return connMySql;

}

道.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)
                }
            }); 

        }
    }); 
}

我尝试实现wait、async和promisse(.then),但没有成功。
同步调用并返回insert id需要什么?
谢谢

gj3fmq9x

gj3fmq9x1#

从mysql repo中,我看到您缺少connection.connect()

dfty9e19

dfty9e192#

连接.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\u连接

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();
            }); 
        }
    }); 
}

相关问题