mysql - 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')”,
如果表名称用单引号括起来,为什么会出现错误?
解决方案
问题是它被作为“值”而不是“标识符”转义。根据您用于执行查询的包,您可以将其标记为应作为标识符进行转义。如果您正在使用该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();
取决于在数据库中配置区分大小写的方式。
推荐阅读
- java - 具有@OneToOne 属性的可嵌入实体
- c - 使用 GTK+2 进行自动化功能 UI 测试
- sql - 如何根据两列的值与另一个表的内连接来计算记录的比率?
- javascript - 我需要使用 onClick 或单击处理程序更改颜色,不知道哪个更好
- python - 如何在不丢失数据点顺序的情况下将 Pandas 中的字符串列表分解为单个列表
- python - 遍历 XML 文件时创建子列表列表
- python - 将函数应用于 Numpy 数组的特定行
- windows - Windows 上的草莓 perl 将不再运行
- android-studio - Android Studio - 无法加载内核绑定,无效的 SDK 哈希??(协议和飞镖)
- wpf - 如何在子用户控件的组合框中触发双击事件?