首页 > 解决方案 > MySQL 使用 node.js 将新对象附加到对象数组中

问题描述

我想使用 JSON_ARRAY_APPEND 将新对象更新为表中的 json 列。当我使用硬代码时它可以工作。但是当我从前端获取数据时,问题就出现了。

代码:'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 'Customer', "Message": 'eqwe', "Time": '9:34 AM'}' AS JSON)) WHERE order_no='Orde' at line 1,sqlState:'42000',索引:0,sql:UPDATE jlk_message_queue SET txn_data = JSON_ARRAY_APPEND(txn_data, '$', CAST('{"MessageId": 5, "UserType": 'Customer', "Message": 'eqwe', "Time": '9:34 AM'}' AS JSON)) WHERE order_no='Order 123'

这似乎是单引号和双引号问题。有没有办法解决这个问题?提前致谢

customerModel.sendChatMessage = function (MessageId, UserType, Message, Time, OrderNo, result) {

    var sql = "UPDATE jlk_message_queue " +
        "SET txn_data = JSON_ARRAY_APPEND(txn_data, '$', " +
        "CAST('{" + '"MessageId": ?, "UserType": ?, "Message": ?, "Time": ?' + "}' AS JSON)) " +
        "WHERE order_no=? ";

// ********Sample data which could work*********
// UPDATE jlk_message_queue
// SET txn_data = JSON_ARRAY_APPEND(txn_data, '$', CAST('{"MessageId": 1, "UserType": "Doctor", "Message": "Hi, This is doctor X, May I help you?", "Time": "12:30 PM"}' AS JSON))
// WHERE order_no='Order 123'


pool.getConnection(function (err, con) {
    if (err) throw err;
    con.query(sql, [MessageId, UserType, Message, Time, OrderNo], function (err, res) {
        if (err) {
            con.destroy();
            result(err, null);
        }
        else {
            console.log(res);

            if (res.affectedRows == 1) {
                result(null, { result: true });
            }
            else {
                result(null, { result: true, value: 'Fail to send message' });
            }

        }
    });
});
};

标签: mysqlnode.js

解决方案


通过使用 JSON_OBJECT 可以解决问题。

var sql = "UPDATE jlk_message_queue " +
    "SET txn_data = JSON_ARRAY_APPEND(txn_data, '$', " +
    "JSON_OBJECT('MessageId', ?, 'UserType', ?, 'Message', ?, 'Time', ?)) " +
    "WHERE order_no=? ";

推荐阅读