Mic*_*ael 1 javascript mysql json
我正在尝试创建一个聊天系统,每次有人发送消息时,它都会添加到我的数据库中该特定人员的 JSON 数组中,但我遇到的问题是当有人尝试使用双引号或" "单引号时在他们的消息中引用'。每当添加带有这些特殊字符的消息时,我都会收到错误:ER_PARSE_ERROR: 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。我在互联网上查找过类似的问题,他们都说我需要用 转义双引号\",但当我使用JSON.stringify method.
不幸的是,这在 JSON 数组中不起作用,而是我必须将双引号替换为\\",但是当我使用该JSON.parse方法时,我在输出中看到反斜杠。如果我只使用单个斜杠,则会出现 SQL 解析错误。
发送的消息包含 ID、时间戳、消息以及发送者的姓名。
[{"ID": 1, "Timestamp": "10/20/2020 11:00 AM", "Msg": "Hello There", "Name": "John"}]
我正在尝试的一个例子如下:
let previousMessages = JSON.parse(this.state.Messages);
let newMsg = `testing double "quotes" and single quote's`
previousMessages.push({ID: previousMessages.length+1, Timestamp: new Date(), Msg: newMsg.replace(/"/g,'\\"'), Name: "John"});
Run Code Online (Sandbox Code Playgroud)
对我的数据库的查询如下所示:
UPDATE table1 SET Messages = "${JSON.stringigy(previousMessages)}" WHERE ID = '1';
// output: UPDATE table1 SET Messages = "[{"ID":1,"Name":"John","Msg":"testing double \\\"quotes\\\" and single quote's","TimeStamp":"10/20/2020 11:00 AM"}]" WHERE ID = '1';
Run Code Online (Sandbox Code Playgroud)
我收到的错误是这样的:
Error: ER_PARSE_ERROR: 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 'ID":1,"Name":"John","Msg":"testing double \\\"quotes\\\" and single quote's","T' at line 2
Run Code Online (Sandbox Code Playgroud)
我尝试过的事情
我尝试过用其他字符替换引号,例如替换'为_which 有效,但似乎每次我想创建消息时都必须这样做。
我也尝试过在 SQL 查询中使用单引号而不是双引号,如下所示: UPDATE table1 SET Messages = '${JSON.stringify(previousMessages)}' WHERE ID = '1'; 但这并没有什么区别
如果有人知道如何在 JSON 数组中转义这些字符,那将会非常有帮助。我觉得必须有一种更简单的方法来转义这些字符,而不是replace为每个字符使用两种不同的方法。
如果您直接编写 SQL,则给定有效的 JSON 文本,您需要:
\n您无需使用双引号执行任何操作。
\n所以 JSON:[1, "John O'Brian", { "hello": "world" }]
会成为Messages='[1, "John O\\'Brian", { "hello": "world" }]'
如果你想用 JS 生成它,那么它看起来像:
\nconst array = [1, "John O'Brian", { "hello": "world" }];\nconst json = JSON.stringify(array);\nconst sql = `UPDATE table1 SET Messages='${json.replace(/\\\\/g, "\\\\\\\\").replace(/'/g, "\\\\'")}' ...`\nRun Code Online (Sandbox Code Playgroud)\n\xe2\x80\xa6 但你不应该这样做。
\n使用允许您使用占位符的 API,并将其留给数据库引擎来确定如何使用引号。它更容易、更不容易出错并且更安全。
\n例如,使用mysqlNPM 的模块:
const array = [1, "John O'Brian", { "hello": "world" }];\nconst json = JSON.stringify(array);\nconnection.query(\n "UPDATE table1 SET Messages=? ....",\n [ json ],\n function (error, results, fields) {\n\n });\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
13994 次 |
| 最近记录: |