In node.js mysql query, check if no matching found

扶醉桌前 提交于 2019-11-29 07:49:54

问题


How can I check if no matching found in mysql (node.js)?

mysql.query("select * from table1 where name = 'abcd'", function(error, result, field) {
    if(error) {
        exist(error); //No error
    } else if(result) {
        console.log(result);  //displays '[]'
        exist(null, result);
    } else {
        exist(null, null); //It is never execute
    }
});
function exist(error, result) {
    if(result)
        console.log("Test:"+result); //Executed and displays 'Test:'
}

My database does not contains name = 'abcd'. So, how can I check if the query does not match?


回答1:


You're receiving an empty array ([]) as result of your query, because as you said, your database does not contain any row with name = 'abcd'.

When you do:

if (result) {
  if (result)
    console.log("Test:" + result);

, you'll enter the if, because Javascript evaluates true for []. Take a look at this article here, that explains how Javascript evaluates true and false values.

A better way to check if your result array is empty is to do:

if (result.length > 0) {
  if (result)
    console.log("Test:" + result);


来源:https://stackoverflow.com/questions/24675125/in-node-js-mysql-query-check-if-no-matching-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!