javascript - 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 中的条件?
解决方案
在 MySQL 中,当您执行读取操作时,它将为您提供 Array 中的值。result.length
因此,通过检查它是否等于 0 来获取结果数组的长度。
当您执行写入或更新操作时,结果将包含一个属性,该属性affectedRows
将告诉您受影响的行数。console.sql('%j', result)
使用并查看 PostGreSQL 中是否有某些选项(很可能有)打印结果。
推荐阅读
- weka - Weka 以波斯语显示数字并使用问号保存数据输出
- python - 在 GPU 中运行代码或以某种方式并行化
- javascript - 表的反应搜索功能
- image - 如何在不裁剪的情况下调整“嵌入”标签内的图像大小?
- pandas - DataFrame 创建 - 推文
- python - 我 rm python3.9 我可以拿回来吗?
- javascript - 我的套接字怎么能留在房间里,所以客户端会收到消息
- java - 时区有冒号时如何解决解析异常?
- python - PySpark 中的语法 df.rdd.map(lambda row: row[0:]) 有什么作用?
- c# - 为什么在 try 块中返回变量不会更改在 finally 部分中重置该变量时返回的值?