Node-postgres:命名参数查询(nodejs)

时间:2022-11-02 01:02:55

I used to name my parameters in my SQL query when preparing it for practical reasons like in php with PDO.

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

So can I use named parameters with node-postgres module?

那么我可以在node-postgres模块中使用命名参数吗?

For now, I saw many examples and docs on internet showing queries like so:

现在,我在互联网上看到很多示例和文档显示如下查询:

client.query("SELECT * FROM foo WHERE id = $1 AND color = $2", [22, 'blue']);

But is this also correct?

但这也是正确的吗?

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

or this

或这个

client.query("SELECT * FROM foo WHERE id = ? AND color = ?", [22, 'blue']);

I'm asking this because of the numbered parameter $n that doesn't help me in the case of queries built dynamically.

我问这个是因为编号参数$ n对于动态构建的查询没有帮助。

2 个解决方案

#1


2  

I have been working with nodejs and postgres. I usually execute queries like this:

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

#2


1  

There is a library for what you are trying to do. Here's how:

有一个图书馆,你正在尝试做什么。就是这样:

var sql = require('yesql').pg

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

#1


2  

I have been working with nodejs and postgres. I usually execute queries like this:

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

#2


1  

There is a library for what you are trying to do. Here's how:

有一个图书馆,你正在尝试做什么。就是这样:

var sql = require('yesql').pg

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