0

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?

4
  • Check the length Commented Oct 9, 2017 at 7:22
  • yes changes made but same error in output Commented Oct 9, 2017 at 7:26
  • Please show the updated code. Also, you have a SQL injection, please use parameterized queries. Commented Oct 9, 2017 at 7:28
  • Possible duplicate of Insert if not exists, else return id in postgresql Commented Oct 9, 2017 at 12:28

1 Answer 1

3

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. 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
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. In addition you can read more about INSERT ... ON CONFLICT statement (usually known as UPSERT) and take care about possible SQL injection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.