繁体   English   中英

在nodejs中使用mssql(用于插入行的函数)

[英]Using mssql in nodejs (function to insert row)

因此,我是Nodejs的新手,现在我尝试根据从客户端收到的操作进行插入。

我有一个功能模块,由路由调用以执行某些任务。 每个动作都需要记录在mssql表中,因此我选择从npm中使用mssql。

https://www.npmjs.com/package/mssql

函数模块中的每个函数都调用saveActionToDB函数,该函数接收到一个操作和一个用户名,以将其插入到表中,如下所示:

function saveActionToDB(action, user){
    if (config.Logging.DB.type == 'mssql'){
        const dbOptions = {
            user: config.Logging.DB.user,
            password: config.Logging.DB.password,
            server: config.Logging.DB.server,
            database: config.Logging.DB.database,
            options: {
                encrypt: config.Logging.DB.encrypt
            }
        };
        const database = require('mssql');
        async () => {
            try{
                const pool = await database.connect(dbOptions);
                const result = await database.query(`insert into actions (action, user) values ("${action}", "${user}")`);
                console.log(pool);
            }
            catch (err){
                console.log(err);
                combinedLogger.error(err);
            }
        }
    }
    else if(config.Logging.DB.type == 'oracle'){
        //oracle
    }
}

该应用程序必须具有使用mssql或oracle的能力。 这就是为什么要检查config.Logging.DB.type val来使用两者的原因。

现在,这些函数调用saveActionToDB,但是它什么也没做。 也没有错误。 我猜这是异步问题。

请注意,我不需要等待saveActionToDB结束就可以响应客户端。

有人可以帮忙吗?

您没有在调用异步函数。 这仅声明一个函数但不执行。 async () => {

看这个例子

console.log('a');
x = async () => {
  console.log('b');
}

console.log('c');
x();

输出是acb 但是如果我这样做

console.log('a');
async () => {
  console.log('b');
}

console.log('c');

输出仅为ac

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM