【问题标题】:Error using mysql in an AWS Lambda function在 AWS Lambda 函数中使用 mysql 时出错
【发布时间】:2020-08-15 08:51:24
【问题描述】:

我创建了一个 AWS Lambda 函数来从 AWS RDS 数据库中检索信息。我还在 AWS API Gateway 中创建了一个触发 Lambda 函数的 API。当我的 SQL 语句是“select * from user”时,API 工作正常。但是,当我尝试“从带有标签 = 人的用户中选择 *”之类的操作时,我收到此错误:

{"errorType":"Error","errorMessage":"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'tag = 'people'' at line 1","trace":["Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'tag = 'people'' at line 1","    at PromisePool.query (/var/task/node_modules/mysql2/promise.js:330:22)","    at Runtime.module.exports.handler (/var/task/index.js:19:38)","    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"]}

我的 AWS Lambda 函数定义为 (Node.js 12.x):

const mysql = require('mysql2');

const pool = mysql.createPool({
    host: process.env.LAMBDA_HOSTNAME,
    user: process.env.LAMBDA_USERNAME,
    password: process.env.LAMBDA_PASSWORD,
    database: process.env.LAMBDA_DATABASE,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

module.exports.handler = async (event, context, callback) => {
    context.callbackWaitsForEmptyLoop = false;
    const tag = event["params"]["querystring"]["tag"]
    const sql = "select * from user with tag = " + tag;

    const promisePool = pool.promise();
    const [rows] = await promisePool.query(sql);
    const lambdaProxyResponse = {
        statusCode: 200,
        body: JSON.stringify([rows])
    };
    return lambdaProxyResponse;
};

有人可以帮我解决这个问题吗?另外,当我在 mysql workbench 中运行命令时,它也能正确执行。

【问题讨论】:

    标签: javascript mysql aws-lambda aws-api-gateway amazon-rds


    【解决方案1】:

    我不确定您的整体环境是什么样的,但首先,以这种方式编写您自己的 SQL 并不是一个好主意。此代码可能会受到 SQL 注入攻击。

    但是,假设您信任输入,这是一个非常简单的解决方法。你需要引号:

    const sql = "select * from user with tag = '" + tag + "'";
    

    请注意,当列是字符串类型时,这是正确的。在数字类型上,您不需要引号。

    如果您信任输入,那么您需要考虑使用某种准备好的语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-20
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2017-06-04
      相关资源
      最近更新 更多