如何在JavaScript中访问SQL请求的结果并将其存储在变量中?
SELECT COUNT(*) FROM account where username='Mashiro';
+----------+
| COUNT(*) |
+----------+
| 9 |
+----------+我的代码:
con.connect(function(err) {
if (err)throw err;
var sql = ("SELECT COUNT(*) FROM account where username=?");
con.query(sql,[username],function (err, result){
if (err)throw err;
console.log(result);
var x = ???????????
return result;
})
})
}我想将x变量设置为'9‘,如下所示:
console.log(x); >>> 9发布于 2020-01-13 01:40:21
使用筛选器选择从表中选择记录时,可以使用"WHERE“语句筛选所选内容:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT COUNT(*) FROM customers WHERE username = ?", [$username], function (err, result) {
if (err) throw err;
console.log(result);
});
});更多示例:https://www.w3schools.com/nodejs/nodejs_mysql_where.asp
使用prepare语句的更多示例:https://evertpot.com/executing-a-mysql-query-in-nodejs/
发布于 2020-01-13 22:29:22
就像这样,我认为它应该是可行的:
con.connect(function(err) {
if (err)throw err;
var sql = ("SELECT COUNT(*) AS count FROM account where username=?");
con.query(sql,[username],function (err, result){
if (err)throw err;
console.log(result[0].count);
var x = result[0].count;
return result;
})
})}
https://stackoverflow.com/questions/59706184
复制相似问题