如何在Node Express项目的Mysql.js表中插入值

时间:2018-07-09 10:47:49

标签: 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上之前,我在insert语句中尝试了多种变体,但对我没有任何帮助。 我该如何实现? 任何帮助都在此先感谢。

2 个答案:

答案 0 :(得分:1)

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

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

下面是使用INSERT INTO

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

答案 1 :(得分:0)

您会尝试这个吗

   let query2 = "INSERT INTO address (id,first_line) VALUES ('userId', 'first_line')"

connection.query(query2, (error, results)