简体   繁体   English

如何在node.js中的mysql包中设置IF条件

[英]How to set up an IF condition within mysql package in node.js

I'm using mysql package for node.js 我正在使用node.js mysql

Studying the documentation did not help me with my question. 研究文档并没有帮助我解决我的问题。 I want to make following: 我想做以下几点:

if (SELECT table_field WHERE id = some_value ){
  // execute some code
} else{
  // execute some code
}

So I want SELECT to return either TRUE or FALSE (like EXISTS operator) 所以我希望SELECT返回TRUEFALSE (如EXISTS运算符)

How can I do so with node.js ? 我怎么能用node.js这样做?

After you setup your connection, you'll want to do something like this: 设置连接后,您将要执行以下操作:

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "SELECT table_field WHERE id = some_value" // setup your query
  con.query(sql, function (err, result) {  // pass your query
    if (err) throw err;
    console.log("Result: " + result);
    if (result) {
      // true logic
    }
    else
    {
      // false logic
    }
  });
});

You can't use the SQL query directly in the IF statement. 您不能直接在IF语句中使用SQL查询。 You need to retrieve the results and then use the results as the boolean value. 您需要检索结果,然后将结果用作布尔值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM