postgresql - "SELECT * FROM $1"准备语句错误到 : error: syntax error at or near "$1"

标签 postgresql prepared-statement pg node-postgres

为什么会出现这个错误?

 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/

相关文章:

postgresql - PostgreSQL View 错误处理

oracle - 如何在从 v$sql 接收到的 Oracle 查询中查找参数?

ruby - 升级到 OSX 10.7.3 Lion 后修复 Postgresql

node.js - 耐克斯 :Error Pool2 - error: password authentication failed for user "username" (Not using UNIX account)

ruby-on-rails - 安装 pg -v 0.17.1

Postgresql - 行到列

python - 无法使用 Python 连接到在不同端口运行的 Postgresql

sql - 是否可以提高该子查询的性能?

php - 迁移到准备好的语句

php - PDO - 查询没有结果