【问题标题】:How to insert json data with special characters like % or ' in MySQL from Nodejs如何从 Nodejs 在 MySQL 中插入带有 % 或 \' 等特殊字符的 json 数据
【发布时间】:2022-10-07 01:17:39
【问题描述】:

我成功了描述1但有错误描述2(存在%) 和描述3(存在\')

如何在插入/更新时转义 JSON 对象值中的此类特殊字符?

注意: 在 mySQL 表中,description 列的数据类型为:JSON

 let description1 =
           {
            text: {
                data: Click Here,
                size: 36,
                alignment: center
                 },
             others: something string
           };
let description2 =
           {
            text: {
                data: Click rate 30%,
                size: 36,
                alignment: center
                 },
             others: something string
           };
 let description3 =
           {
            text: {
                data: Click Here,
                size: 36,
                alignment: center
                 },
             others: something special alamin\'s string
           };
 let dbConf = {
                connectionLimit: parseInt(DB_POOL_MAX),
                host: DB_HOST,
                user: DB_USERNAME,
                password: DB_PASSWORD,
                database: DB_DATABASE,
                multipleStatements: true
            };
const dbConnection = makeDb(dbConf);
const dbConnectionObject = util.promisify(dbConnection.query).bind(dbConnection);
let sql = `INSERT INTO product_description (product_id, description) VALUES (\'${pdid}\',\'${JSON.stringify(description})\')`;
let result = await dbConnectionObject(sql);
  • 如何在 MySQL 中插入带有 % 或 \' 等特殊字符的 json 数据根据 MySQL 语言规则,这些符号必须在提供的字符串文字值中进行转义。 dev.mysql.com/doc/refman/8.0/en/string-literals.html
  • 十分感谢!如果它是单个字符串,那么我可以使用转义字符串文字,但对于复杂的 JSON。能否请您给我一个示例查询/示例,说明我将如何将其用作 JSON 对象? { \"list\": [ { \"id\": 1, \"name\": \"Sample Category\", \"description\": \"Lorem Ipsum 100% book.\" }, { \ "id\": 2, \"name\": \"Sample Category\", \"description\": \"自 1500 年代以来,Lorem Ipsum 一直是行业的标准虚拟文本\" } ], \ "sort\": 3, \"title\": \"Sample Title\", \"status\": true, \"details\": \"Sample Offer\", \"subtitle\": \"Sample提供\” }

标签: mysql node.js json


【解决方案1】:

由于字符('),因此如果您尝试在替换字符后插入 JSON.stringify 数据("'") 带字符("\'") 然后它会工作。你可以尝试如下。

var data = JSON.stringify(description3);
data = data.split("'").join("\\'");
const dbConnection = makeDb(dbConf);
const dbConnectionObject =util.promisify(dbConnection.query).bind(dbConnection);
let sql = `INSERT INTO product_description (product_id, description) VALUES ('${pdid}','${data})')`;
let result = await dbConnectionObject(sql);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 2018-06-21
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
相关资源
最近更新 更多