我想访问包含计数元素实际数量的变量,但我不知道如何。
sql = "SELECT COUNT(id) FROM users WHERE username='" + req.body.username + "' AND password='" + req.body.password + "';";
con.query(sql, function (err, result) {
if (err) throw err;
})
result
是:[ RowDataPacket { 'COUNT(id)': 0 } ]
;我无法使用语法result.COUNT(id)访问数据,因为出现错误:ReferenceError: id is not defined
答案 0 :(得分:1)
为count
使用别名,为了更好地抽象,请在查询中使用模板文字
sql = `SELECT COUNT(id) as count FROM users WHERE username=${req.body.username} AND password=${req.body.password}`;
con.query(sql, function (err, result) {
if (err) throw err;
})
对于[RowDataPacket {'total':0}],请尝试
sql = `SELECT COUNT(id) as count FROM users WHERE username=${req.body.username} AND password=${req.body.password}`;
con.query(sql, function (err, result) {
if (err) throw err;
else{
let results=JSON.parse(JSON.stringify(result)) // gives you an js object array
} })
答案 1 :(得分:0)
给您的字段一个别名(标签)
sql = "SELECT COUNT(id) as total FROM users WHERE username='" + req.body.username + "' AND password='" + req.body.password + "';";
结果将为[ RowDataPacket { 'total': 0 } ]