首页 > 解决方案 > REST API Javascript如何编写检查SQL查询是否返回0行的条件

问题描述

我有db机场,有TABLE游客,其中有COLUMN:id,还有TABLE:航班,还有列:listoftouristsbyid,它是整数数组。我需要检查我是否传递给 REST API 请求整数,该整数是旅游者的 id,但不存在。表示没有给定 id 的游客(id 是主键,自动递增键)。我写了这样的东西:

app.post('/flights', function(req, res) {
    pool.connect(function(err,client,done) {
        if(err) {
            return console.log("Error fetching clients", err);
        }
        client.query("SELECT tourists.id FROM tourists WHERE tourists.id = " + req.body.listoftouristsbyid[i], function (err, result) {
            done();
            if (result.rows === 0) {
                return console.log("Tourist "+req.body.listoftouristsbyid[i]+" you want to add does not exist" + err);
            }
        })
        client.query('INSERT INTO flights(departuredate, arrivaldate, numberofseats, listoftouristsbyid, ticketprice) VALUES($1, $2, $3, $4, $5)', 
            [req.body.departuredate, req.body.arrivaldate, req.body.numberofseats, req.body.listoftouristsbyid, req.body.ticketprice]);
        done();
        res.redirect('/flights');
    })
})

我知道它是一个有效的查询,因为当我在 PSQL shell 中输入它时它会返回

airport=#                                                                  
SELECT tourists.id FROM tourists WHERE tourists.id = 15;
 id 
----
(0 rows)

但它不能作为 javascript 代码工作 - 意味着代码应该以错误终止,但条件不满足。我如何在 SELECT Tourist.id FROM Tourist WHERE Tourist.id = 15 给出 0 行时捕获 Javascript 中的条件?

标签: javascriptsqlnode.jspostgresqlrest

解决方案


在 MySQL 中,当您执行读取操作时,它将为您提供 Array 中的值。result.length 因此,通过检查它是否等于 0 来获取结果数组的长度。

当您执行写入或更新操作时,结果将包含一个属性,该属性affectedRows 将告诉您受影响的行数。console.sql('%j', result)使用并查看 PostGreSQL 中是否有某些选项(很可能有)打印结果。


推荐阅读