出于实际原因,我过去常常在SQL查询中命名参数,就像在使用PDO的php中一样。
那么我可以在node-postgres模块中使用命名参数吗?
目前,我在互联网上看到了许多示例和文档,显示了如下查询:
client.query("SELECT * FROM foo WHERE id = $1 AND color = $2", [22, 'blue']);但这也是正确的吗?
client.query("SELECT * FROM foo WHERE id = :id AND color = :color", {id: 22, color: 'blue'});或者这个
client.query("SELECT * FROM foo WHERE id = ? AND color = ?", [22, 'blue']);我之所以这样问,是因为编号参数$n在动态构建查询的情况下对我没有帮助。
发布于 2016-11-17 04:42:08
对于你想要做的事情,有一个library。下面是操作步骤:
var sql = require('yesql').pg
client.query(sql("SELECT * FROM foo WHERE id = :id AND color = :color")({id: 22, color: 'blue'}));发布于 2021-11-19 18:46:29
QueryConvert帮了大忙。它将接受一个参数化的sql字符串和一个对象,并将其转换为pg一致的查询配置。
type QueryReducerArray = [string, any[], number];
export function queryConvert(parameterizedSql: string, params: Dict<any>) {
const [text, values] = Object.entries(params).reduce(
([sql, array, index], [key, value]) => [sql.replace(`:${key}`, `$${index}`), [...array, value], index + 1] as QueryReducerArray,
[parameterizedSql, [], 1] as QueryReducerArray
);
return { text, values };
}用法如下:
client.query(queryConvert("SELECT * FROM foo WHERE id = :id AND color = :color", {id: 22, color: 'blue'}));发布于 2015-09-16 21:45:09
我一直在使用nodejs和postgres。我通常像这样执行查询:
client.query("DELETE FROM vehiculo WHERE vehiculo_id= $1", [id], function (err, result){ //Delete a record in de db
if(err){
client.end();//Close de data base conection
//Error code here
}
else{
client.end();
//Some code here
}
});https://stackoverflow.com/questions/32610213
复制相似问题