AWS Lambda函数中使用mysql错误

问题描述 投票:0回答:1

我创建了一个AWS Lambda函数,以从AWS RDS数据库检索信息。我还在AWS API Gateway中创建了一个触发Lambda函数的API。当我的SQL语句为“从用户选择*”时,API可以正常工作。但是,当我尝试类似“从带有标签= people的用户中选择*”时,出现此错误:

{"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工作台中运行命令时,它会正确执行。

javascript mysql aws-lambda aws-api-gateway amazon-rds
1个回答
0
投票

我不太肯定您的总体环境如何,但是首先要这样编写自己的SQL并不是一个好主意。此代码可能会受到SQL注入攻击。

但是,假设您信任输入,这是一个非常简单的修复。您需要引号:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.