简体   繁体   English

如何使用 AWS Lambda (nodeJS) 查询 AWS 外部的 MySQL 数据库?

[英]How can I query a MySQL database that is outside AWS, using AWS Lambda (nodeJS)?

I haven't been able to access to an external database from AWS Lambda, is it actually possible?我无法从 AWS Lambda 访问外部数据库,这真的可能吗? Am I doing something wrong?难道我做错了什么?

(I have already install mysql through npm locally and imported the .zip with the modules into the console) (我已经在本地通过 npm 安装了 mysql 并将带有模块的 .zip 导入控制台)

Thanks!谢谢!

var mysql = require('mysql');
var config = require('./config.json');

var pool = mysql.createPool({
    host: config.dbHost,
    user: config.dbUser,
    password: config.dbPassword,
    database: config.dbName
})

exports.handler = (event,context,callback) => {
    context.callbackWaitsForEmptyEventLoop = false;
    pool.getConnection(function(error,connection){
        connection.query(`SELECT * from dot LIMIT 10`,function (error,results,fields){
            connection.release();
            if (error) callback(error);
            else callback(null,results);
        });
    });
};

I get the following response:我收到以下回复:

{
  "errorType": "TypeError",
  "errorMessage": "Cannot read property 'query' of undefined",
  "trace": [
    "TypeError: Cannot read property 'query' of undefined",
    "    at /var/task/index.js:18:21",
    "    at Handshake.onConnect (/var/task/node_modules/mysql/lib/Pool.js:58:9)",
    "    at Handshake.<anonymous> (/var/task/node_modules/mysql/lib/Connection.js:526:10)",
    "    at Handshake._callback (/var/task/node_modules/mysql/lib/Connection.js:488:16)",
    "    at Handshake.Sequence.end (/var/task/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)",
    "    at Protocol.handleNetworkError (/var/task/node_modules/mysql/lib/protocol/Protocol.js:369:14)",
    "    at PoolConnection.Connection._handleNetworkError (/var/task/node_modules/mysql/lib/Connection.js:418:18)",
    "    at Socket.emit (events.js:376:20)",
    "    at emitErrorNT (internal/streams/destroy.js:106:8)",
    "    at emitErrorCloseNT (internal/streams/destroy.js:74:3)"
  ]
}

Is this endpoint somewhere in your AWS account?此端点是否位于您的 AWS 账户中? If so, and your MYSQL db is in a VPC, then if you configure your Lambda to run in the same VPC, then you will be able to access it.如果是这样,并且您的 MYSQL 数据库位于 VPC 中,那么如果您将 Lambda 配置为在同一 VPC 中运行,那么您将能够访问它。

Otherwise, the endpoint would have to be accessible through the internet.否则,端点将必须可通过 Internet 访问。 I would try to ping your DB endpoint from inside Lambda and see if that works.我会尝试从 Lambda 内部 ping 您的数据库端点,看看是否有效。

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

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