Node.js – PostgresSQL – 无法确定参数$ 1错误的数据types

我正在尝试使用node.js pg npm包创build一个PostgreSQL准备语句。 但是,我不断收到错误:

无法确定参数$ 1的数据types

  function promiseQuery(sql, values) { return new Promise(function(resolve, reject) { pool.query('select $1 from workers', ['name'], function(err, result) { if (err) {console.log(err); reject(err)} else resolve(result.rows); }) }); } 

在数据库name字段被设置为inputtext not null

我也尝试pg-promise ,但也没有成功。

在查询中select name from workers ,从SQL语法 name的angular度来看就是一个identifier ,标识符永远不能作为$Nparameter passing,它们必须在命令中逐字显示。 否则,查询不能被准备。

$N参数只能出现在查询中文字(常量)所在的位置。

如果在任何客户端库之外尝试使用与PREPARE SQL命令类似的东西,则会出现相同的错误:

 PREPARE p as SELECT $1 FROM pg_class; ERROR: could not determine data type of parameter $1 

解决scheme是在提交到数据库之前,使用stringreplace技术为列名或表名创build查询。

DanielVérité的答案延伸…

你不能将Prepared Statements和dynamic列名结合起来,你必须在客户端生成查询。

使用SQL名称的 pg-promise语法,你可以像这样正确地转义你的查询:

 db.any('SELECT $1~ FROM table', [colName]) // OR: db.any('SELECT $1:name FROM table', [colName]) // OR: db.any('SELECT ${colName~} FROM table', {colName}) // OR: db.any('SELECT ${colName:name} FROM table', {colName}) // Etc, other variable syntax, like $[], $//, $<>, $() 

如果你想做一个列表的列表,那么最简单的方法是这样的:

 const colNames = ['one', 'two', 'three']; db.any('SELECT $1~ FROM table', [colNames]) // etc, the same variations as above, all will generate: // SELECT "one","two","three" FROM table 

或从所有对象属性:

 const data = { one: 123, two: true, three: 'text' }; db.any('SELECT $1~ FROM table', [data]) // etc, the same variations as above, all will generate: // SELECT "one","two","three" FROM table 

所有这些方法将正确地转义查询,确保SQL注入是不可能的。