【问题标题】:In node.js mysql query, check if no matching found在 node.js mysql 查询中,检查是否没有找到匹配项
【发布时间】:2014-08-31 17:52:25
【问题描述】:

如何检查 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'。那么,如何检查查询是否不匹配?

【问题讨论】:

    标签: javascript mysql node.js node-mysql


    【解决方案1】:

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

    当你这样做时:

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

    ,您将输入 if,因为 JavaScript 将 true 计算为 []。看看 this article here,它解释了 JavaScript 如何评估 true 和 false 值。

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

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

    【讨论】:

    • if (!result.length) 在这里可以正常工作。
    • @BenFortune 同意,因为 Javascript 将 false 评估为 0。只是我喜欢那种冗长的代码编写方式。
    • 不应该是(if result.isArray() && result.length > 0) ??不管怎样,本的“负面”更好
    • @BenFortune 对我来说效果不佳。对我有用的是if(result.length != 0) 或大于。
    • 如果result.length大于0,为什么还要检查if result?
    猜你喜欢
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2017-07-24
    相关资源
    最近更新 更多