【问题标题】:NodeJs IF Statement in AWS Lambda using MySQL database使用 MySQL 数据库的 AWS Lambda 中的 NodeJs IF 语句
【发布时间】:2020-11-14 21:33:15
【问题描述】:

我正在尝试在 NodeJS 中为以下任一查询传递 IF 语句(表中存在 IF 数据,[true] 更新数据,[false] 插入数据):

var mysql = require('mysql');
var config = require('./config.json');
var pool  = mysql.createPool({
    host     : config.dbhost,
    user     : config.dbuser,
    password : config.dbpassword,
    database : config.dbname
  });

exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  pool.getConnection(function(err, connection) {

      // IF STATEMENT
      var id = ... //select statement to the same table...??
      If (id = ?) {

          // If TRUE
          connection.query('UPDATE table SET email = "'johndoe@icloud.com'" WHERE id = 1;', function (error, results, fields) {
          // And done with the connection.
          connection.release();
          // Handle error after the release.
          if (error) callback(error) ;
          else callback(null, results);,
 
          // If FALSE
          connection.query('INSERT INTO table (id, name, email) VALUES (1, "'John Doe'", "'johndoe@gmail.com'");', event['i'], function (error, results, fields) {
          // And done with the connection.
          connection.release();
          // Handle error after the release.
          if (error) callback(error) ;
          else callback(null, results);

      }; 
    });
  });
};

我是 NodeJS 的新手,我仍在尝试使用上面的代码找出 IF 语句。我会及时通知你的。

@CHRISWILLIAMS 得出他的答案的详细信息

基本上,我有 2 个 API。

第一个 API 最初运行,如果存在则删除 canvass_prices。这个我没有任何问题。这是第一个 API 的结果:

Response:
[
  {
    "ID": 1,
    "Item": "Earth Science Deep Conditioning Masque For Hair - 2 Fl Oz",
    "Qty": 30,
    "Container": "Bottle",
    "Size": "750ml",
    "Reiciendis eos nostrum ut sequi.": 1680,
    "Sed quidem aspernatur quisquam ut.": 19920,
    "Aut dolorem repellendus iste nisi...": 79170
  }
]

Request ID:
"e2bbe38b-8121-4cb5-aa88-ac570b066759"

Function logs:
START RequestId: e2bbe38b-8121-4cb5-aa88-ac570b066759 Version: $LATEST
END RequestId: e2bbe38b-8121-4cb5-aa88-ac570b066759
REPORT RequestId: e2bbe38b-8121-4cb5-aa88-ac570b066759  Duration: 287.67 ms Billed Duration: 300 ms Memory Size: 128 MB Max Memory Used: 74 MB

这是我遇到问题的第二个 API(请参阅此处的第一次更新)。此 API 将更新第一个 API 创建的 canvass_prices。

但是,我第一次点击的结果是这样的:

Response:
[
  {
    "ID": 1,
    "Item": "Earth Science Deep Conditioning Masque For Hair - 2 Fl Oz",
    "Qty": 30,
    "Container": "Bottle",
    "Size": "750ml",
    "Reiciendis eos nostrum ut sequi.": 1680,
    "Sed quidem aspernatur quisquam ut.": 19920,
    "Aut dolorem repellendus iste nisi...": 79170,
    "Voluptates laudantium voluptas nam.": null,
    "Ipsum voluptatem dolorum commodi.": null
  }
]

Request ID:
"4aed4c97-8ef6-485c-93b4-ca2eaf95703d"

Function logs:
START RequestId: 4aed4c97-8ef6-485c-93b4-ca2eaf95703d Version: $LATEST
END RequestId: 4aed4c97-8ef6-485c-93b4-ca2eaf95703d
REPORT RequestId: 4aed4c97-8ef6-485c-93b4-ca2eaf95703d  Duration: 393.79 ms Billed Duration: 400 ms Memory Size: 128 MB Max Memory Used: 75 MB

第二次及后续点击解决了我的问题,它返回了正确的结果,并且不会进一步返回重复的“ID”。

Response:
[
  {
    "ID": 1,
    "Item": "Earth Science Deep Conditioning Masque For Hair - 2 Fl Oz",
    "Qty": 30,
    "Container": "Bottle",
    "Size": "750ml",
    "Reiciendis eos nostrum ut sequi.": 1680,
    "Sed quidem aspernatur quisquam ut.": 19920,
    "Aut dolorem repellendus iste nisi...": 79170,
    "Voluptates laudantium voluptas nam.": null,
    "Ipsum voluptatem dolorum commodi.": null
  },
  {
    "ID": 9,
    "Item": "Laci Le Beau Maximum Strength Super Dieter's Tea Cinnamon Spice - 12 Tea Bags",
    "Qty": 10,
    "Container": "Bottle",
    "Size": "750ml",
    "Reiciendis eos nostrum ut sequi.": null,
    "Sed quidem aspernatur quisquam ut.": 30,
    "Aut dolorem repellendus iste nisi...": null,
    "Voluptates laudantium voluptas nam.": 1510,
    "Ipsum voluptatem dolorum commodi.": 17910
  }
]

Request ID:
"de40d4fa-06bb-433f-81d0-d667b2e2bca6"

Function logs:
START RequestId: de40d4fa-06bb-433f-81d0-d667b2e2bca6 Version: $LATEST
END RequestId: de40d4fa-06bb-433f-81d0-d667b2e2bca6
REPORT RequestId: de40d4fa-06bb-433f-81d0-d667b2e2bca6  Duration: 70.41 ms  Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 75 MB

我想知道为什么它会在第二次点击时出现。

【问题讨论】:

  • 查看您的报价,您有一个单引号查询字符串,带有一个带引号的电子邮件。引用的电子邮件结束第一个字符串。注意语法高亮。使用不同的引用样式,例如外部的双引号 " 和内部的单引号。如果需求发生变化则翻转。
  • 同时使用insert ... on duplicate key update ..,您将不会受到竞争条件的影响。
  • 感谢您的建议。除了查询之外,我在 IF STATEMENT 上的 nodejs 代码遇到了问题,其中变量从表中引用。
  • 如果你使用insert ... on duplicate key udpate ...,你就不是一个 IF 语句。如果结果不管,它就会达到结果。在这个问题中,您的电子邮件地址是否故意不同?你想要 id 等于什么?这与查询中的 ID 相同吗?
  • @danblack 是的,电子邮件地址完全不同。如果记录存在,则需要更新以进行电子邮件更正。如果没有,则将其插入。但是,这 2 个查询已经在工作。我的主要问题是这部分。我不知道如何正确地做到这一点。 var id = ... //select 语句到同一个表...??如果 (id == ?) {

标签: mysql node.js amazon-web-services aws-lambda


【解决方案1】:

假设这只是一个 NodeJS 的答案,那么问题是你是 = 而不是 ==。单等号将 Id 分配给您要比较的值,而双等号是等于的表示法。还有=== 与相同(== 不关心类型,因此 5=='5' 为真,而失败为相同)。

下面是固定代码。

var mysql = require('mysql');
var config = require('./config.json');
var pool  = mysql.createPool({
    host     : config.dbhost,
    user     : config.dbuser,
    password : config.dbpassword,
    database : config.dbname
  });

exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  pool.getConnection(function(err, connection) {

      // IF STATEMENT
      connection.query('SELECT id from table where id = ?', [event['id']], function (error, results, fields) {
          if (results.length > 0) {

              // If TRUE
              connection.query('UPDATE table SET email = "'johndoe@icloud.com'" WHERE id = 1;', function (error, results, fields) {
              // And done with the connection.
              connection.release();
              // Handle error after the release.
              if (error) callback(error) ;
              else callback(null, results);,
     
              // If FALSE
              connection.query('INSERT INTO table (id, name, email) VALUES (1, "'John Doe'", "'johndoe@gmail.com'");', event['i'], function (error, results, fields) {
              // And done with the connection.
              connection.release();
              // Handle error after the release.
              if (error) callback(error) ;
              else callback(null, results);

          }; 
        });
    });
  });

【讨论】:

  • 在这段代码中 if (id == ?) { 如何分配事件参数,就像我们在查询中所做的那样。这 ?是我指定为参数的变量。
  • 您只需输入变量名,例如,如果这来自 event['id'] 您将拥有 id == event['id']
  • 什么!那是多么容易?让我回到你身边。我现在就试试。
  • 这假定 id 是您从查询中后处理的特定值
  • 已经更新了代码,我认为这正是你想要的
【解决方案2】:

或者没有 if 语句和竞争条件:

exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  pool.getConnection(function(err, connection) {
      connection.query('INSERT INTO table (id, name, email)
        VALUES (1, "John Doe", "johndoe@gmail.com")
        ON DUPLICATE KEY UPDATE table email = "johndoe@icloud.com";', function (error, results, fields) {
          // And done with the connection.
          connection.release();
          // Handle error after the release.
          if (error) callback(error) ;
          else callback(null, results);
      }; 
    });
  });

这假定id 是表中的主键或唯一键。

【讨论】:

  • 我喜欢您的解决方案更简洁直接,但请您在更新中查看我的解决方案。我很难弄清楚错误来自哪里。请承担我在上面的更新中分享了我的确切代码。
  • 突然之间这是一个完全不同的问题/问题。 INSERT 不是一个可以作为结果放置到 CONCAT 的函数,它本身就是一个声明。尝试在dba.stackexchange.com 上再次以纯 SQL 问题的形式询问您要插入的内容和一些表结构。您的查询中有太多DISTINCTs,并且用户变量方面看起来很奇怪。您所针对的 mysql 版本也会有所帮助。
  • 我明白了。对于那个很抱歉。但是这里的情况可以仅限于您的建议。有准备好的语句,执行,释放之后,但我不想显示以隔离错误。
  • 澄清:参考您在解决方案中指出的事件['id'],它是否需要作为 ON DUPLICATE KEY UPDATE 的主要参考?
  • 删除event[id],这是一个错误。主要引用来自查询的insert 部分中的id。
猜你喜欢
  • 2021-09-13
  • 2017-07-24
  • 1970-01-01
  • 2019-10-13
  • 2015-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
相关资源
最近更新 更多