【问题标题】:Node-postgres: named parameters query (nodejs)Node-postgres:命名参数查询(nodejs)
【发布时间】:2015-12-13 03:14:54
【问题描述】:

出于实际原因,例如在带有 PDO 的 php 中,我曾经在 SQL 查询中命名我的参数。

那么我可以在 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 在动态构建查询的情况下对我没有帮助。

【问题讨论】:

标签: sql node.js query-parameters node-postgres


【解决方案1】:

不完全是 OP 的要求。但你也可以使用:

import SQL from 'sql-template-strings';

client.query(SQL`SELECT * FROM unicorn WHERE color = ${colorName}`)

它使用标签函数结合模板文字来嵌入值

【讨论】:

    【解决方案2】:

    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'}));
    

    【讨论】:

    • 谢谢!良好的util函数,不需要为此使用库
    • @ArtemKolodko 请在下面查看我的最新答案。我认为它更整洁:)
    【解决方案3】:

    有一个library 表示您正在尝试做的事情。方法如下:

    var sql = require('yesql').pg
    
    client.query(sql("SELECT * FROM foo WHERE id = :id AND color = :color")({id: 22, color: 'blue'}));
    

    【讨论】:

    • 至少,一年后似乎是一个新的解决方案!我会尽快试一试并告诉你。谢谢:)
    • 很棒的库,但我更喜欢基于第一原则(不需要库)的 SO 答案的答案,并提及库以供参考,以防 OP 需要。
    【解决方案4】:

    我一直在使用 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
        }
      });
    

    【讨论】:

    • 是的,我省略了回调,但问题仍然存在。
    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 2016-03-18
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 2019-12-17
    相关资源
    最近更新 更多