[英]How to UPDATE a mySQL table with JSON Object in Node.js?
I have a JSON Object and want to UPDATE a mySQL table, without List all of the Keys我有一个 JSON Object 并想更新一个 mySQL 表,没有列出所有的键
with an INSERT I do this like用 INSERT 我这样做
var arrayValue = Object.keys(obj).map(function(key) {
return String("'"+obj[key]+"'");
});
var arrayKeys = Object.keys(obj).map(function(key) {
return String(key);
});
var sql = "INSERT INTO `modules` "+ " (" +arrayKeys.join() + ") VALUES ("+arrayValue.join()+");";
con.query(sql, function (err, result, fields) {
if (err) throw err;
return result;
});
The same i would do with UPDATE我也会对 UPDATE 做同样的事情
How can i do this?我怎样才能做到这一点?
does this fill your needs?这能满足您的需求吗?
const object = {
id: 1,
firstName: "John",
lastName: "Doe"
};
const columns = Object.keys(object);
const values = Object.values(object);
let sql = "INSERT INTO tableName ('" + columns.join("','") +"') VALUES (";
for (let i = 0; i < values.length; i++) {
sql += "?";
if (i !== values.length - 1) {
sql += ",";
}
}
sql+= ")";
connection.query(sql, values, (error, result, fields) => {
//do what you must here.
});
For update:对于更新:
const object = {
id: 1,
firstName: "John",
lastName: "Doe"
};
const columns = Object.keys(object);
const values = Object.values(object);
let sql = "UPDATE tableName SET '" + columns.join("' = ? ,'") +"' = ?";
connection.query(sql, values, (error, result, fields) => {
//do what you must here.
});
Off course what would you put in the where statement?当然,您会在 where 语句中添加什么?
I hope this helped.我希望这会有所帮助。
here the example这里的例子
/ Update an existing user
app.put('/users/:id', (request, response) => {
const id = request.params.id;
pool.query('UPDATE users SET ? WHERE id = ?', [request.body, id], (error, result) => {
if (error) throw error;
response.send('User updated successfully.');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.