mysql - 如何将值插入到 Node Express 项目中的 Mysql.js 表中

标签 mysql node.js express mysqljs

这是我的用例。

  1. 首先,我将数据插入客户表。
  2. 然后我获取客户的 insertId。
  3. 然后我尝试使用该 ID 将数据插入地址表中。

async function createCustomer(req, res, next) {
    const customer = {
        type: req.body.type,
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        email: req.body.email
    };
    
    const first_line = req.body.first_line

    console.log("Customer from front-end", customer);

    try {
        let query1 = "INSERT INTO customer_supplier SET ?";
        connection.query(query1, customer, (error, results) => {
            if (error) {
                console.log("Error", error);
            } else {
                let userId = results.insertId;
                let query2 = "INSERT INTO address (id,first_line) VALUES ?";


                connection.query(query2, [userId, first_line], (error, results) => {
                    if (error) {
                        console.log("error in address ==================================", error)

                    } else {
                        res.json({
                            results: results
                        })
                    }
                })
            }
        });

      
    } catch (error) {
        console.log("error from", error);
        res.json({
            error: error
        });
    }
}

但是当我尝试将数据插入地址表时,

code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'36\' at line 1',
  sqlState: '42000',
  index: 0,
  sql: 'INSERT INTO address (id,first_line) VALUES 36' }

在把这个问题放到 stackoverflow 上之前,我在插入语句中尝试了很多变体,但没有任何效果对我有用。 我如何实现这一目标?

最佳答案

您的sql写得不正确,您需要添加()来包装该值

let query2 = "INSERT INTO address (id,first_line) VALUES (?,?)";

下面是使用INSERT INTO的语法

> INSERT INTO table_name (column1, column2, column3, ...) 
> VALUES (value1, value2, value3, ...);

关于mysql - 如何将值插入到 Node Express 项目中的 Mysql.js 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51243754/

相关文章:

node.js - Express response 采用request方式

mysql - 自动将数据从数据库导出到 CSV 文件

php - 通过 Laravel/Eloquent 插入 MySQL 行时出现问题

javascript - 在 Express 中接收 POST 请求时登录

node.js - Swagger JSDoc 中的 VSCode 缩进

javascript - 如何读取 Node 中发出的简单http请求的响应

php - 如何使用 shell_exec 和 plesk 11 注册邮件?

MYSQL游标循环,多跑一轮,为什么?

node.js - 在 Express/Node.js 中维护请求范围

node.js - 在 AWS Codebuild 上运行时 Jest 不关闭()ing expressjs 服务器