[英]How can I access the result of a SQL request in NodeJS?
如何在 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
使用過濾器選擇當從表中選擇記錄時,您可以使用“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
更多帶有准備語句的示例等: https : //evertpot.com/executing-a-mysql-query-in-nodejs/
像這樣我認為它應該工作:
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;
})
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.