如何在AWS lambda中使用NodeJS执行SQL查询?

osh3o9ms  于 2022-09-21  发布在  Node.js
关注(0)|答案(1)|浏览(177)
exports.handler = async (event) => {
    const sql = require('mssql');

    let config = {
        user: "MyUsername",
        password: "MyPassword",
        server: "MyServer",
        port: 1433,
        options: {
            database: 'MyDatabase',
            encrypt: false,
        }
    };

    sql.connect(config, (err) => {
        if (err) { console.log(err);}
        else {
            console.log('connected');

            let request = new sql.Request();
            const theQuery = "SELECT * FROM MyTable";

            request.query(theQuery, (err, data)=> {
                if(err) { console.log(err); }
                else { console.log(data); }
            })
       }
    });
};

我正尝试用它执行一个简单的SELECT查询,在本地运行它时似乎运行得很好,但当我在Lambda上尝试它时,它超时了。我的lambda与SQL Server在同一个vPC上,因此不存在连接问题。有什么好主意吗?

2022-07-17T03:10:02.912Z    a4775342-517a-4511-920e-46269ee07627    INFO    ConnectionError: Failed to connect to********:1433 in 15000ms
    at /opt/nodejs/node_modules/mssql/lib/tedious/connection-pool.js:70:17
    at Connection.onConnect (/opt/nodejs/node_modules/tedious/lib/connection.js:1051:9)
    at Object.onceWrapper (node:events:642:26)
    at Connection.emit (node:events:527:28)
    at Connection.emit (node:domain:475:12)
    at Connection.emit (/opt/nodejs/node_modules/tedious/lib/connection.js:1079:18)
    at Connection.connectTimeout (/opt/nodejs/node_modules/tedious/lib/connection.js:1284:10)
    at Timeout._onTimeout (/opt/nodejs/node_modules/tedious/lib/connection.js:1229:12)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7) {
  code: 'ETIMEOUT',
  originalError: ConnectionError: Failed to connect to********:1433 in 15000ms
      at Connection.connectTimeout (/opt/nodejs/node_modules/tedious/lib/connection.js:1284:26)
      at Timeout._onTimeout (/opt/nodejs/node_modules/tedious/lib/connection.js:1229:12)
      at listOnTimeout (node:internal/timers:559:17)
      at processTimers (node:internal/timers:502:7) {
    code: 'ETIMEOUT',
    isTransient: undefined
  }
}
k7fdbhmy

k7fdbhmy1#

事实证明,剧本只是在结束之前就结束了。要修复此问题,请使用I had to return a promise

exports.handler = async (event) => {

    const promise = new Promise(function(resolve, reject) {

        let sql = require('mssql');

        sql.connect(config, (err) => {
            if (err) {
                reject(err);
            }

            else {
                const request = new sql.Request();

                const query = "SELECT * FROM MyTable";
                request.query(query, (err, result) => {
                    if(err) {
                        reject(err);
                    }

                    else {
                        resolve(result);
                    }
                });
            }
        });
    });

    return promise;
};

相关问题