2016-01-20 102 views
0

沒有解決方法我在我的搜索中找到了解決此問題的方法。我試圖在SQLite3中製作一個簡單的引用存儲程序。確定Node.js中是否存在SQLite行

app.get('/quote/:id', function(req, res) { 
if (exists) { 
    db.serialize(function() { 
     db.each("SELECT rowid AS id, text, author FROM quotes WHERE rowid = " + req.params.id, function(err, row) { 
      if (row != null && row != undefined && row != []) { 
       return res.send("Text: '" + row.text + "'<br>Author: " + row.author); 
       console.log("Found that match!"); 
       match = true; 
      } 
      else { 
       return res.send("Error 404!") 
      } 
      if (err) { 
       console.log(err); 
      } 
     }); 
    }); 
} 
else if (req.params.id < quotes.length && req.params.id >= 0) { 
    res.send(quotes[req.params.id]); 
    console.log("taking from the offline database"); 
} 
}); 

但是當我進入了一個不存在的,而不是顯示錯誤404,一個id,頁面只是不斷加載,直到超時:當我輸入一個報價ID確實存在下面的代碼工作。我相信問題可能是db.each函數根本不會被調用,如果所需的行不存在,但我該如何解決這個問題?是否有可能檢查是否存在,然後顯示404如果不是?

回答

1

可以使用EXISTS或COUNT執行單獨的查詢。

但是如果你想確保你的回調總是被調用,添加另一行查詢:(該LIMIT clause省略了NULL列時,一些數據發現)

SELECT id, text, author FROM ... WHERE ... 
UNION ALL 
SELECT NULL, NULL, NULL 
LIMIT 1; 

+0

非常感謝!當我將if(row!= null)'改爲'if(row.text!= null)'時,這就像一個魅力一樣! –