【问题标题】:How to UPDATE a mySQL table with JSON Object in Node.js?如何在 Node.js 中使用 JSON 对象更新 mySQL 表?
【发布时间】:2020-03-18 20:32:26
【问题描述】:

我有一个 JSON 对象,想更新一个 mySQL 表,但没有列出所有键

使用 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;
    });

我会用 UPDATE 做同样的事情

我该怎么做?

【问题讨论】:

  • 你能用 JSON 对象更新问题吗?你的更新查询究竟是什么是来自那个 json 对象的 mysql。

标签: javascript mysql node.js typescript


【解决方案1】:

这能满足您的需求吗?

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.
});

更新:

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.
});

当然,你会在 where 语句中添加什么?

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    这里是例子

    / 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

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    相关资源
    最近更新 更多