虽然我能够连接和插入,但无法从Lambda更新MySQL(AWS RDS)表

时间:2018-10-12 10:29:56

标签: mysql amazon-web-services aws-lambda

下面是我的lambda函数。来自APIAPI Gateway)的请求。即使我尝试将值直接传递到更新表,它也不会更新。 我可以通过INSERT API到同一表中的数据。只是想知道这里出了什么问题。

感谢任何帮助。预先感谢。


var mysql = require('mysql');
var config = require('./config.json');
var sql,response;

exports.handler = function(event, context) {
    var connection = mysql.createConnection({
      host     : config.dbhost,
      user     : config.dbuser,
      password : config.dbpassword,
      database : config.dbname
    });

exports.handler = function(event, context,callback) {
   //prevent timeout from waiting event loop
  context.callbackWaitsForEmptyEventLoop = false;

   var variable1= event.variable1;
   var variable2= event.variable2;
   var id= event.id;

    connection.query('UPDATE LocationData SET latitude = ?,longitude =? WHERE userId = ?', [variable1, variable2,id], function(error, results, fields) {
        response = {};
        response['id'] = results.id;
        response['variable1'] = results.variable1;
        response['variable2'] = results.variable2;
        context.succeed(response);
    });

};
};

1 个答案:

答案 0 :(得分:0)

您错过了对connect函数的调用。一个有效的示例如下:

var mysql = require('mysql');
var config = require('./config.json');

exports.handler = function(event, context) {
  var connection = mysql.createConnection({
    host     : config.dbhost,
    user     : config.dbuser,
    password : config.dbpassword,
    database : config.dbname
  });
  connection.connect(); // <--- MISSING THIS!

  exports.handler = function(event, context,callback) {
    context.callbackWaitsForEmptyEventLoop = false;

    var variable1 = event.variable1;
    var variable2 = event.variable2;
    var id = event.id;

    var sql = 'UPDATE LocationData SET variable1=?,variable2=? WHERE userId=?';
    connection.query(sql, [variable1, variable2, id], function(error, results, fields) {
      context.succeed({
        id: results.id,
        variable1: results.variable1,
        variable2: results.variable2
      });
    });
  };
};

此外,作为一般建议,万一出问题了,您应该始终检查回调中的错误变量,并对此做出相应的反应。