如何在node express项目的mysql.js表中插入值

7gyucuyw  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(355)

这是我的用例。
首先,我将数据插入customer表。
然后我为客户获取插入的ID。
然后我尝试使用该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语句中尝试了太多的变体,但没有任何东西适合我。我如何做到这一点?

gtlvzcf8

gtlvzcf81#

您的sql写得不正确,您需要添加 () Package 值

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

下面是要使用的语法 INSERT INTO ```

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

fhity93d

fhity93d2#

你能试试这个吗

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

connection.query(query2, (error, results)

相关问题