【问题标题】:Store JSON as string in Azure SQL Database将 JSON 作为字符串存储在 Azure SQL 数据库中
【发布时间】:2020-03-31 22:14:25
【问题描述】:

我正在尝试将 JSON 作为字符串插入 Azure SQL 数据库的表中。 “信息”列被创建为 nvarchar(max)。但是我尝试了两种方式都出现错误:

尝试 1: 将 JSON 作为对象发送

INSERT INTO productsTable (Id, Name, Url, Info) VALUES (123456, 'Name of product', 'https://www.example.com/product/123456', {'test':'here','nested':{'itest':' ivalue','itest2':100}})

导致错误:

"error": {
  "code": "EREQUEST",
  "originalError": {
     "info": {
        "name": "ERROR",
        "event": "errorMessage",
        "number": 102,
        "state": 1,
        "class": 15,
        "message": "Incorrect syntax near 'test'.",
        "serverName": "myapp",
        "procName": "",
        "lineNumber": 1
     }
  }

尝试 2: JSON.stringify json 在发送写入之前。

INSERT INTO CampaignDetailsTable (Id, Name, Url, Info) VALUES (123456, 'Name of produc', 'https://www.example.com/product/123456', '{\'test\':\'here\',\'nested\':{\'itest\':\'ivalue\',\'itest2\':100}}')

导致同样的错误:

"code": "EREQUEST",
"originalError": {
  "info": {
     "name": "ERROR",
     "event": "errorMessage",
     "number": 102,
     "state": 1,
     "class": 15,
     "message": "Incorrect syntax near 'test'.",
     "serverName": "myapp",
     "procName": "",
     "lineNumber": 1
  }

}

我不关心它以什么格式存储在 SQL 中,只要我读回代码后可以在我的代码中恢复为 JSON 对象即可。

【问题讨论】:

标签: node.js json sql-server


【解决方案1】:

这只是一个和其他字符串一样的字符串,所以至少需要用单引号括起来:

'My String'

你的字符串恰好有单引号,所以你需要转义:

'you''re doing it wrong'

我把你的例子贴在这里

https://www.freeformatter.com/sql-escape.html

它给了我这个:

{''test'':''here'',''nested'':{''itest'':''ivalue'',''itest2'':100}}

你只需要用引号括起来,因为它是一个字符串文字。所以这就是你插入的内容。

'{''test'':''here'',''nested'':{''itest'':''ivalue'',''itest2'':100}}'

在管理工作室中运行它来测试:

SELECT '{''test'':''here'',''nested'':{''itest'':''ivalue'',''itest2'':100}}'

【讨论】:

  • 谢谢@Nick.McDermaid。我还尝试将其设为失败的字符串文字,现在我看到我应该用另一个单引号转义单引号。我已经准备好了。
  • 参数化查询而不是转义引号不是更好吗?不正确地转义字符串并将它们连接到查询中是 SQL 注入攻击发生的一种方式。
  • 是的,这样会更好。
  • @alroc ,我可以为 Azure 存储表进行参数化。但是我还没有找到任何方法来为 Azure SQL 插入做到这一点。我正在使用 node.js 和 mssql,我正在使用的命令是:-------------------------------- -------- sql.connect(dbConfig) .then(pool => { return pool.request() .query(jsonQueryPacket.query); }) ------------- ------ 我会问一个关于如何参数化它的单独问题。但是,如果您有任何快速的建议,那么我很乐意尝试。
  • @Curious101 查看stackoverflow.com/a/48289995/1324345 以使用 node.js 参数化查询
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
  • 2014-02-18
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多