首页 > 解决方案 > Nodejs Mysql:Query-Escaping 添加单引号

问题描述

我试图逃避我的 SQL 创建表查询。它将单引号添加到导致错误的查询中。

    let table = "SomeTable";
    let query_table = 
    "CREATE TABLE IF NOT EXISTS ? (ID_Charge int AUTO_INCREMENT PRIMARY KEY, ID_Machine int, FOREIGN KEY (ID_Maschine) REFERENCES Machine (ID_Machine))";

    con.query(query_table, `${table}_Users` (err) => {
    (...)

我得到的错误是这样的:

“您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,了解在 ''SomeTable_Users' 附近使用的正确语法(第 1 行的 ID_Charge int AUTO_INCREMENT PRIMARY KEY, ID_Maschine int')”,

如果表名称用单引号括起来,为什么会出现错误?

标签: mysqlsqlnode.jsescaping

解决方案


问题是它被作为“值”而不是“标识符”转义。根据您用于执行查询的包,您可以将其标记为应作为标识符进行转义。如果您正在使用该mysql软件包,您可以执行以下操作:

let table = "SomeTable";
let query_table = 
"CREATE TABLE IF NOT EXISTS ?? (ID_Charge int AUTO_INCREMENT PRIMARY KEY, ID_Machine int, FOREIGN KEY (ID_Maschine) REFERENCES Machine (ID_Machine))";

con.query(query_table, [`${table}_Users`], (err) => {
(...)

注意 double 的??意思是“这是一个标识符,而不是一个值”。

如果您使用@databases/mysql作为驱动程序,您可以:

con.query(sql`
  CREATE TABLE IF NOT EXISTS ${sql.ident(`${table}_Users`)}
  (
    ID_Charge int AUTO_INCREMENT PRIMARY KEY,
    ID_Machine int,
    FOREIGN KEY (ID_Maschine) REFERENCES Machine (ID_Machine)
  )`
);

请参阅https://www.atdatabases.org/docs/sql#sqlidentnames

注意,根据您的库的使用方式,您可能还希望使用以下内容将允许的表名列入白名单:

if (!['table1', 'table2'].includes(table)) throw new Error('Invalid table name');

您可能还需要使用

`${table}_Users`.toLowerCase();

取决于在数据库中配置区分大小写的方式。


推荐阅读