【问题标题】:How to insert values into Mysql.js table in Node express project如何将值插入到 Node express 项目中的 Mysql.js 表中
【发布时间】:2018-07-09 10:47:49
【问题描述】:

这是我的用例。

  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 上之前,我在插入语句中尝试了很多变体,但对我没有任何作用。 我如何做到这一点?

【问题讨论】:

  • 检查地址表中id字段的数据类型。我认为它是地址表中的整数,您正在从结果中获取字符串。

标签: mysql node.js express mysqljs


【解决方案1】:

你的sql写的不对,需要加上()把值换行

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

下面是INSERT INTO使用的语法

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

【讨论】:

    【解决方案2】:

    你会试试这个

       let query2 = "INSERT INTO address (id,first_line) VALUES ('userId', 'first_line')"
    
    connection.query(query2, (error, results)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2017-07-10
      • 1970-01-01
      相关资源
      最近更新 更多