为什么会出现这个错误?
const response = await pool.query(`SELECT * FROM $1`, [table]);
[table]
的值在我的测试用例中是["person"]
。但它不断出错:
error: syntax error at or near "$1"
最佳答案
您不能将占位符 ($1
) 用于标识符(例如列名和表名),占位符仅用于值;您可以将其视为 'name'
(一个值)和 var name
(一个标识符)之间的区别。
您可以改用字符串操作,并且您需要将标识符列入白名单以避免出现问题:
const safeTables = [ 'person', ... ]; // Known safe values.
if(!safeTables.includes(table)) {
// throw an exception, return an error, ...
}
const response = await pool.query(`SELECT * FROM ${table}`);
此字符串插值是安全的,因为您只允许已知的安全值。您还可以使用知道如何正确引用标识符的函数(例如 escape.ident
from pg-escape )。
关于postgresql - "SELECT * FROM $1"准备语句错误到 : error: syntax error at or near "$1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50265852/