[英]in nodejs how to insert the record into PostgreSQL if it does not exist?
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"}); }); } });
it displays university_name as exist even it is not present on every entry, how to insert the record into PostgreSQL if does not exists? 即使没有在每个条目上都显示,它也会显示university_name存在,如果不存在,如何将记录插入PostgreSQL?
It depends on which DB driver you are using, anyway most common is that when SELECT query is executed, you will get result data even if records in the DB doesn't exists. 这取决于您使用的是哪个DB驱动程序,无论如何,最常见的是在执行SELECT查询时,即使数据库中的记录不存在,您也将获得结果数据。 Usually result object then has property rows which you should check. 通常,结果对象会包含应检查的属性行。
In your case similar to this: 您的情况与此类似:
if(data.rows && data.rows.length > 0){
// there is data in the DB
} else {
// no data in the DB
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.