我试图在程序开始时插入在 javascript 中定义的值。但它不喜欢我尝试插入变量,相反,我应该输入原始名称。
这是错误代码:
错误:ER_BAD_FIELD_ERROR:“字段列表”中存在未知列“用户名”
我正在使用 SQL 数据库和 javascript 与其交互。该值已预先用变量定义。
var username = "Mark Graham"
var password = 13.00
con.connect(function(err) {
var username = "Mark Graham"
var password = 13.00
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO staff (name, hours) VALUES (username, password)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
它应该将 Mark Graham 插入数据库。
最佳答案
实现 ORM、Sequelize 或使用
connection.query('INSERT INTO staff (name, hours) VALUES (?, ?)', [YourVar,YourSecondVar], function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
或
connection.query({
sql: 'INSERT INTO staff (name, hours) VALUES (?, ?)',
timeout: 40000, // 40s
values: [varOne,varTwo]
}, function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
关于javascript - 如何通过变量将数据插入MySQL数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56066776/