在node.js mysql查询中,检查是否没有找到匹配

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

本文关键字:是否 检查 js node mysql 查询      更新时间:2023-09-26

如何检查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:'
}

我的数据库不包含name = 'abcd'。那么,如何检查查询是否不匹配呢?

您正在接收一个空数组([])作为您的查询结果,因为正如您所说,您的数据库不包含name = 'abcd' 的任何行。

当你这样做的时候:

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

,您将输入if,因为JavaScript为[]计算true。看看这篇文章,它解释了JavaScript如何计算truefalse的值。

检查结果数组是否为空的更好方法是:

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