使用postgres和node js在单个语句中执行多个查询

时间:2016-02-25 10:59:34

标签: sql node.js postgresql

我需要在像这样的单个语句中执行insert和delete查询

INSERT INTO COMPANY (ID,NAME) VALUES (1, 'Paul');DELETE FROM  COMPANY WHERE ID='12';

这是我执行查询的node.js代码

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

我收到了像这样的错误消息

  

错误:无法将多个命令插入预准备语句

是否可以使用node.js?

在postgresql数据库中执行多个查询

2 个答案:

答案 0 :(得分:2)

试试这个

pg.connect(pgConString, function (err, client, done) {
    if (err) {
        callBack("DB connection failed. " + err, null);
        return;
    }
    client.query({
        text: "INSERT INTO COMPANY (ID,NAME) VALUES (1, 'Paul');",
        values: [1, "Poul1"],
        name: "insertQuery"
    });

    client.query({
        text: "DELETE FROM  COMPANY WHERE ID='12';",
        name: "deleteQuery"
    });

    client.on("error", function (err) {
        callBack("DB insertion failed. Error Message: " + err, null);
        return;
    });


});

答案 1 :(得分:0)

当使用 pg-promise...

首先,我们通过一个灵活的 QueryFormat 列表声明我们的查询 + 值:

const queries = [
    {query: 'select * from products where price > $1', values: [12.5]},
    {query: 'select * from payments where amount < ${amount}', values: {amount}}
];

然后我们创建一个单查询格式的字符串:

const sql = pgp.helpers.concat(queries);

然后我们执行它,并检索结果:

const [products, payments] = await db.multi(sql);

参见:concatmulti