通过 nodejs 插入数据时 SQL 中的语法错误

Syntax error in SQL when inserting data via nodejs

我在 pipedream 中有一个简单的 nodejs 代码,它将正文电子邮件发送到 mySQL 数据库。 我已经检查了与数据库的连接及其工作。 这是我的代码

const mysql = require('mysql2/promise');

const { host, port, username, password, database } = auths.mysql

const connection = await mysql.createConnection({
  host,
  port,//3306
  user:"u648845344_demo",
  password,
  database,
});

const [rows, fields] = await connection.execute(
  "INSERT INTO Testing (Email) VALUES (${JSON.stringify(steps.trigger.event.body.email)})"
  );
console.log(rows);
//console.log(${JSON.stringify(steps.trigger.event.body.email)})

我收到错误

ErrorYou have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '{JSON.stringify(steps.trigger.event.body.email)})' at line 1 at PromiseConnection.execute (/tmp/ee/node_modules/mysql2/promise.js:110:22) at Object.module.exports (/steps/mysql.js:14:41) at process._tickCallback (internal/process/next_tick.js:68:7)

我尝试在控制台日志中获取电子邮件,但我收到的错误是

TypeError [ERR_INVALID_ARG_TYPE]The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type undefined

这是一个经典的 SQL 注入错误,using prepared statements 很容易修复它:

const [rows, fields] = await connection.execute(
  "INSERT INTO Testing (Email) VALUES (?)",
  [ steps.trigger.event.body.email ]
);

如果您编写的查询没有数据,只有占位符,并使用类似这样的方法通过驱动程序将数据添加到查询中,您将不会产生任何 SQL 注入错误。这些是一种极其严重的错误形式,因为如果发现一个错误,可能会给您、您的项目和您所从事的任何业务带来灾难性的后果。

Using JSON.stringify for SQL protection is, and I cannot stress this enough, completely and wildly inappropriate. That escapes JSON and only JSON. You must use SQL-specific escaping functions if that occasion arises, but use prepared statements with placeholder values whenever possible.