我需要更好地理解字符串,转义和存储在mysql数据库中。任务看上去很简单,但逃跑后我遇到了一些麻烦。因此,我很乐意就以下问题作出一般解释:
我尝试的是将javascript对象存储在mysql DB中。在发送之前,它可以很好地处理字符串。把它从DB中拿回来,只需解析它,一切都很好。
let myObj = {
name: 'Paul',
age: '24'
}
现在,我的对象中还有一条消息,它可以具有特殊字符:
let myObj = {
name: 'Paul',
age: '24',
message: 'message with special characters: ',`´"~'
}
也没问题,我开始逃跑了。结果:
let myObj = {
name: 'Paul',
age: '24',
message: 'message with special characters: \'\,\`´\"\~'
}
如果我对对象进行了紧张化,就会得到以下结果:
{
"name": "Paul",
"age": "24",
"message": "message with special characters: \\'\\,\\`´\\\"\\~"
}
将其发送到mysql会产生以下错误:
(节点:13077) UnhandledPromiseRejectionWarning:错误: ER_PARSE_ERROR:您的SQL语法出现了错误;检查与MariaDB服务器版本对应的手册,以获得在'\,‘“}附近使用的正确语法
由于错误,我操作了特殊字符并删除了附加的'\'
,结果如下:
obj.message = obj.message(/\\\\/g,'\\');
产出:
{
"name": "Paul",
"age": "24",
"message": "message with special characters: \'\,\`´\\"\~"
}
一切都很好,数据被传输到DB,我的mysql更新查询不再失败。
问题
更进一步。这条消息包含了一个新行:
产出紧张:
{
"name": "Paul",
"age": "24",
"message": "message with special characters: \'\,\`´\n\\"\~"
}
将它发送到DB,我得到以下条目(其中\n:我得到了一个新行):
{"name":"Paul","age":"24","message":"message with special characters: ',`´
\"~"}
这会导致将其解析回来的错误。下面是日志(服务器端)先前的解析(错误是有意义的):
{"name":"Paul","age":"24","message":"\',`´\n' +
'\\"~"}
问题
\n
也逃脱?这意味着DB条目是正确的,而DB不使用\n
启动新行?为任何解释/帮助而高兴!
发布于 2022-09-01 22:59:07
我不知道方法是正确的还是简单的,但当我需要将用户生成的字段作为JSON插入MYSQL数据库时,我就是这样做的
string_cleanJSON_preStringify(str)
{
if(!str.replace) return str;
str=str.replace(/'/g,"\\'"); //escape all at least ' once
str=str.replace(/"/g,'\\"'); //escape all at least " once
str=str.replace(/[\t\r\n\f]/g,''); // remove problematic escape characters
if(str.charAt(str.length-1) == '\\') str+=' '; // add blank space at the end if \ is last character - for example: {"var":"\"} would be problematic
return str;
}
string_cleanJSON_to_query(str)
{
str = str.replace(/(\\)+\\/g,'\\'); // replace all \ more than 1 in a row, to be just 1 ( \\ -> gets escaped again when it's processed to just \)
str = str.replace(/(\\)+"/g,'\\\\\\"'); // replace all \" more than 1 (ex \\\") - i don't know why \\\\\\ - this seem to work in my case, might need to alter based on str manipulations before insert
str = str.replace(/(\\)+'/g,"\\'"); // i don't know why \\ - this seem to work in my case, might need to alter based on str manipulations before insert
str = str.replace(/(\\)+t/g,"t"); // same process as above but with problematic escape characters
str = str.replace(/(\\)+r/g,"r");
str = str.replace(/(\\)+n/g,"n");
str = str.replace(/(\\)+f/g,"f");
return str;
}
我如何使用它来获得一个查询:
let o = {field_data:string_cleanJSON_preStringify(user_gen_field_data)}
let j = string_cleanJSON_to_query(JSON.stringify(o));
let q = `INSERT INTO blabla (json) VALUES('${j}')`;
https://stackoverflow.com/questions/71407310
复制相似问题