I need to execute insert and delete query in a single statement like this
INSERT INTO COMPANY (ID,NAME) VALUES (1, 'Paul');DELETE FROM COMPANY WHERE ID='12';
This is my node.js code for executing query
pg.connect(pgConString, function (err, client, done) {
if (err) {
callBack("DB connection failed. " + err, null);
return;
}
var query = client.query({
text: "INSERT INTO COMPANY (ID,NAME) VALUES (1, 'Paul');DELETE FROM COMPANY WHERE ID='12';"
values: [1, "Poul1"],
name: "insertQuery"
});
query.on("error", function (err) {
callBack("DB insertion failed. Error Message: " + err, null);
return;
});
query.on('end', function (result) {
done();
return;
});
});
I got error message like this
error: cannot insert multiple commands into a prepared statement
is it possible to execute multiple queries in postgresql database using node.js ?
You can write multiple psql commands and SQL statements in one text file (say, named statements. sql ), and then use the command psql congress -af statements. sql to execute them all. Use “ ; ” to signal the end of each SQL statement in the file.
To run multiple statements in one query with node-mysql, we can call connection. query with all our SQL statements. connection. query('SELECT ?; SELECT ?
To run a query with multiple statements, ensure that each statement is separated by a semicolon; then set the DSQEC_RUN_MQ global variable to 1 and run the query. When the variable is set to zero, all statements after the first semicolon are ignored.
Essentially, node-postgres is a collection of Node. js modules for interfacing with a PostgreSQL database. Among the many features node-postgres supports include callbacks, promises, async/await, connection pooling, prepared statements, cursors, rich type parsing, and C/C++ bindings.
Although there is an accepted answer, it's a bit obsolete. For now node-postgres handles multiple queries in one call and returns a neat little array to you, like:
const db.query('select 1; select 2; select 3;')
results.map(r => (r.rows[0]['?column?']))
// [ 1, 2, 3 ]
There is also an alternative 'opinionated' library, called pg-promise, which also accepts query chains in one call and works with sql
files as well.
When using pg-promise...
First, we declare our queries + values via a flexible QueryFormat list:
const queries = [
{query: 'select * from products where price > $1', values: [12.5]},
{query: 'select * from payments where amount < ${amount}', values: {amount}}
];
Then we create a single-query formatted string:
const sql = pgp.helpers.concat(queries);
And then we execute it, and retrieve the result:
const [products, payments] = await db.multi(sql);
See: concat, multi.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With