在nodejs中如何将记录插入到PostgreSQL中,如果它不存在?
问题描述:
在nodejs中如何将记录插入到PostgreSQL中,如果它不存在?
router.post('/university', function (req, res, next) {
pg.connect(connectionString,function(err,client,done) {
if(err){
console.log("not able to get connection "+ err);
res.status(400).send(err);
}
client.query("select university_name from university where university_name = '"+req.body.university_name+"'",function(err,data)
{
if(data) {
res.send({message:"exist"});
}
else
{
client.query("INSERT INTO university (_id, university_name, status) VALUES (nextval('university_id_seq'), '"+req.body.university_name+"', '"+req.body.status+"')", function(err, result) {
done();
if(err){
console.log(err);
res.status(400).send(err);
}
res.send({message : "successfully inserted"});
});
}
});
它显示UNIVERSITY_NAME的存在,甚至它不存在于每个条目, 如何插入记录到PostgreSQL的,如果它不存在?
答
这要看数据库驱动程序您正在使用,反正最常见的是执行SELECT查询时,你会得到结果的数据,即使在DB的记录不存在。通常结果对象具有您应该检查的属性行。
在你的情况与此类似:
if(data.rows && data.rows.length > 0){
// there is data in the DB
} else {
// no data in the DB
}
+0
我有输出... !!!谢谢 –
+0
不客气。此外,您可以阅读有关INSERT ... ON CONFLICT语句(通常称为UPSERT)的更多信息,并注意可能的SQL注入。 – Dario
检查'length'做出 – jcaron
肯定的变化,但在输出 –
同样的错误,请出示更新的代码。另外,你有一个** SQL注入**,请使用参数化查询。 – jcaron