【问题标题】:the data is not pushed into mysql table数据未推送到 mysql 表中
【发布时间】:2021-07-14 18:04:31
【问题描述】:

connection.query("SELECT email, password FROM authenticate where email=?", email,
    function (error, result) {
      if (error) {
        throw error;
      } else {
        if (result.length == 0) {
          console.log('name not available');
          res.sendFile(path.join(__dirname + "/public/applyFailure.html"));
        } else if (result[0].password == password) {
          console.log(userData);
          connection.query("INSERT INTO userapplications SET ? ", userData,
            function (error, result, fields) {
              if (error){
                throw error;
              } 
              else{
                console.warn("insertion successful");
                res.sendFile(path.join(__dirname + "/public/applySuccess.html"));
              }   
            });
        } else {
          console.log('invalid user and password');
          res.sendFile(path.join(__dirname + "/public/apply.html"))
        }
      }
    });
  connection.end();
错误:

调用退出后无法将查询入队。

由于某种原因,数据库已连接,数据未添加到表中。 我是初学者。

【问题讨论】:

  • userData的值是多少?
  • 它是一个简单的对象
  • db connected { education: 'BE in CSE/ISE', design: 'Artificial Inteligence (Python)', userView: '222' }
  • 是的。我无法弄清楚。我正在尝试在不同表的查询中查询不同的表。这会产生任何问题吗? `

标签: mysql node.js express mysql-error-1064


【解决方案1】:

将您的connection.end(); 移动到回调中,如下所示。

connection.query("SELECT email, password FROM authenticate where email=?", email,
    function (error, result) {
      if (error) {
        connection.end();
        throw error;
      } else {
        if (result.length == 0) {
          console.log('name not available');
          res.sendFile(path.join(__dirname + "/public/applyFailure.html"));
        } else if (result[0].password == password) {
          console.log(userData);
          connection.query("INSERT INTO userapplications SET ? ", userData,
            function (error, result, fields) {
              if (error){
                connection.end();
                throw error;
              } 
              else{
                console.warn("insertion successful");
                res.sendFile(path.join(__dirname + "/public/applySuccess.html"));
                connection.end();
              }   
            });
        } else {
          console.log('invalid user and password');
          res.sendFile(path.join(__dirname + "/public/apply.html"))
          connection.end();
        }
      }
    });
  connection.end();

类似这样,你可以进行更改。

【讨论】:

    【解决方案2】:

    我认为这是因为 NodeJS 的异步特性。尝试将 connection.end() 与 connection.query() 连接起来。

    喜欢:

    connection.query("your_code_here).end();
    

    【讨论】:

    • 我现在没有收到错误,但我没有看到任何内容插入到我的 MySQL 表中:(
    • 其实需要在回调函数里面。放在那里仍然会在插入之前同步调用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多