这是我的用例。
- 首先,我将数据插入客户表。
- 然后我获取客户的 insertId。
- 然后我尝试使用该 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/