在node.js mysql查询中,检查是否找不到匹配项 [英] In node.js mysql query, check if no matching found
问题描述
如何检查mysql(node.js)中是否找不到匹配项?
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:'
}
我的数据库不包含名称='abcd'.那么,如何检查查询是否不匹配?
My database does not contains name = 'abcd'. So, how can I check if the query does not match?
推荐答案
作为查询的结果,您将收到一个空数组([]
),因为如您所说,您的数据库不包含任何行与name = 'abcd'
.
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'
.
当您这样做:
if (result) {
if (result)
console.log("Test:" + result);
,您将输入if
,因为Javascript将true
评估为[]
.看看此处的这篇文章,解释了Javascript如何评估true
和false
值.
, 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);
这篇关于在node.js mysql查询中,检查是否找不到匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!