关于javascript:如何通过pg-promise传递表名和参数

How to pass table names and parameters with pg-promise

我是node的新手,其后是pg-promise。我要在我的节点快速应用程序中尝试实现的一条路由将作为api来在数据库的表中进行单个字段更新。这仅是一条路由,将使用表名,列名,列值和列ID值来调用该路由,以标识表中要更新的行。

这是我到目前为止尝试过的代码,但似乎无法正确理解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
router.post('/update_db_field', function (req, res, next) {
    db.one('update $table~ set $dbcol~=$dbcolval~ where $dbcolid~=$dbcolidval~ returning $colid~', [
        req.body.table,
        req.body.dbcol,
        req.body.dbcolid,
        req.body.dbcolval,
        req.body.dbcolidval
    ]).then(function (data) {
        console.log(data)
        res.send(data)
    }).catch(function (error) {
        console.log("ERROR:", error.message || error); // print error;
    });
})

很遗憾,它抛出以下错误:

ERROR: syntax error at or near"$"

是否还有一种方法可以从catch()函数打印查询字符串,从而使调试更容易一些?


您将变量格式与命名参数混淆,您的查询应为:

1
2
3
4
5
6
7
8
9
10
router.post('/update_db_field', function (req, res, next) {
    db.one('UPDATE ${table~} SET ${dbcol~} = ${dbcolval} WHERE ${dbcolid~} = {dbcolidval} RETURNING ${colid~}', req.body, a => a[req.body.dbcolid])
    .then(function (dbcolid) {
        console.log(dbcold)
        res.send(dbcolid)
    })
    .catch(function (error) {
        console.log("ERROR:", error.message || error); // print error;
    });
})

尽管您仍然可能会遇到问题,因为传递动态表列意味着您不知道如何将其转换为正确的类型,因此,例如,您可能最终将dbcolval作为字符串,尽管它必须是整数,然后查询将因此而拒绝。

请注意,我们添加了可选的a => a[req.body.dbcolid],因此它不是使用具有一个属性的对象来解析,而是直接使用属性值来解析。

How can I see the query text printed in console?

1
2
var query = pgp.as.format(query, values);
console.log(query);

API:as.format。