Node -postgres: named parameters query (nodejs)

I used my parameters in my SQL query when preparing it for practical reasons, for example, in php with PDO.

Can I use named parameters with the node-postgres module?

Currently, I have seen many examples and documents on the Internet showing such queries:

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

But is that also correct?

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

or

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

I ask about this because of the numbered parameter $n, which does not help me in the case of dynamic queries.

+4
source share
2 answers

I worked with nodejs and postgres. I usually execute queries as follows:

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
source

, . :

var sql = require('yesql').pg

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

Source: https://habr.com/ru/post/1607658/


All Articles