2017-10-09 63 views
0

在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的,如果它不存在?

+0

檢查'length'做出 – jcaron

+0

肯定的變化,但在輸出 –

+0

同樣的錯誤,請出示更新的代碼。另外,你有一個** SQL注入**,請使用參數化查詢。 – jcaron

回答

3

這要看數據庫驅動程序您正在使用,反正最常見的是執行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

相關問題