首页 > 解决方案 > 有没有办法使用 node.js 知道 mysql 表中是否存在一行?

问题描述

我正在尝试创建一个函数,如果它检测到包含 nodejs 中特定列中的值的行,则返回 true。

我尝试使用 query() 中的结果变量但没有成功:

let rowexists = (mystring) => {
    let exists = false;
    let sql = "SELECT EXISTS( SELECT 1 FROM mytable WHERE `mycolumn` = '" + mystring + "')";

    connection.query(sql, function(error, result, field){
        console.log((result[sql]));
        console.log(exists);
        exists = (result[sql]);
    });
    return exists;
}

console.log(rowexists("myvalue"));

事件如果存在值为“myvalue”的行(存在),rowexists() 始终返回 false。

重要编辑:

我的问题不在于这是异步的,而在于两者都是

console.log((result[sql]));

console.log(exists);

返回未定义。

标签: javascriptmysqlnode.js

解决方案


承诺是在这种情况下有用的东西。

您遇到的问题是您的查询在函数返回时尚未完成运行。因此,返回一个 Promise 后,我们可以稍后返回该值。

旁注:在使用 SQL 数据库时,您应该使用准备好的查询。

let rowexists = (mystring) => {
  // Return a new promise
  return new Promise(resolve => {
    // Create the sql query (this uses placeholders)
    // Hard coded values don't need to be placeholders but just for example:
    let sql = "SELECT 1 FROM ?? WHERE ?? = ?";
    // Query the database replacing the ?? and ? with actual data
    connection.query(sql, ['mytable', 'mycolumn', mystring], function(error, result, field){
      // Result will either be undefined or a row.
      // Convert it to a boolean and return it.
      resolve(!!result)
    });
  });
}

// Get the data
rowexists("myvalue").then(result => console.log(result))

使用 async/await 的自调用函数:

(async function() {
  let exists = await rowexists('myothervalue')
  console.log(exists)
  // The rest of your related code
})()

如果你不喜欢then()语法,你可以使用async/await. 您可以通过以下两种方式执行此操作:

使用 async/await 的基本功能:

async function test() {
  let exists = await rowexists('mythrirdvalue')
  console.log(exists)
  // The rest of your related code
}

test()

推荐阅读