mysql - 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' });
}
}
});
});
};
解决方案
通过使用 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=? ";
推荐阅读
- sql - SQL 一对多从多对多的关系
- r - 从 group1、group2、overlap_count 创建一个重叠矩阵?
- c++ - 为什么`std::this_thread::sleep_for` 函数拒绝在 WSL Ubuntu 上休眠?
- docker - 在docker中,“减少build-index组件的缓存间隔”是什么意思
- python - 如何使用 sys.stdin 在 python 中只读取第一个空行
- java - java中表达式的别名
- sql - 如何比较一个数据库表的列与另一列的相似性
- c# - 我需要将此 powershell 代码转换为 C#,因为我无法设置执行策略来运行 powershell 脚本
- c# - 如何在 C# 中将字符串与字符串数组进行比较?
- nestjs - 如何在 NestJS 拦截器中获取存储库