admin管理员组文章数量:1393874
I have a JSON Object and want to UPDATE a mySQL table, without List all of the Keys
with an INSERT I do this like
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
How can i do this?
I have a JSON Object and want to UPDATE a mySQL table, without List all of the Keys
with an INSERT I do this like
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
How can i do this?
Share Improve this question asked Nov 22, 2019 at 18:26 Michael MitchMichael Mitch 4332 gold badges8 silver badges19 bronze badges 1- Can you update the question with the JSON object and what exactly would be your update query is mysql from that json object. – ambianBeing Commented Nov 22, 2019 at 20:05
2 Answers
Reset to default 4does 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?
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.');
});
});
that works for me
本文标签: javascriptHow to UPDATE a mySQL table with JSON Object in NodejsStack Overflow
版权声明:本文标题:javascript - How to UPDATE a mySQL table with JSON Object in Node.js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744083555a2588097.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论