【问题标题】:How can I access the result of a SQL request in NodeJS?如何在 NodeJS 中访问 SQL 请求的结果?
【发布时间】:2020-01-12 17:06:54
【问题描述】:

如何在 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

【问题讨论】:

  • 提供的信息没有人可以回答。您使用的是哪个库?
  • 尝试使用以下 sql-query: SELECT COUNT(*) as count FROM account where username=?" 然后使用 result[0].count 访问。SQL 总是返回一个数组,所以你有使用索引访问。count 是您设置的属性 as

标签: javascript mysql sql node.js


【解决方案1】:

使用过滤器选择 从表中选择记录时,您可以使用“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/

【讨论】:

    【解决方案2】:

    像这样我认为它应该可以工作:

    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;
        })
    })
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多