简体   繁体   English

将 json 文件存储在 MS SQL 中

[英]Store json file in MS SQL

I have a JSON file, how to store a JSON file in MS SQL?我有一个 JSON 文件,如何在 MS SQL 中存储 JSON 文件? And read the file data after storing it into Database?并在将文件数据存储到数据库后读取文件数据?

I'm using a python script to interact with SQL Server.我正在使用 python 脚本与 SQL 服务器进行交互。

Note: I don't want to store key-value pairs as an individual records in DB, I want to store the whole file in DB using python.注意:我不想将键值对作为单独的记录存储在 DB 中,我想使用 python 将整个文件存储在 DB 中。

There is no specific data type for JSON in SQL Server, unlike say XML which has the xml data type. SQL 服务器中的 JSON 没有特定的数据类型,不像xml数据类型为 Z0F63A70E0F32ZE674。

If you are, however, storing JSON data in SQL Server then you will want to use an nvarchar(MAX) .但是,如果您要在 SQL 服务器中存储 JSON 数据,那么您将需要使用nvarchar(MAX) If you are on SQL Server 2016+ I also recommend adding a CHECK CONSTRAINT to the column to ensure that the JSON is valid, as otherwise parsing it (in SQL) will be impossible.如果您在 SQL Server 2016+ 上,我还建议在列中添加CHECK CONSTRAINT以确保 JSON 有效,否则将无法解析它(在 SQL 中)。 You can check if a value is valid JSON using ISJSON .您可以使用ISJSON For example, if you were adding the column to an existing table:例如,如果您要将列添加到现有表中:

ALTER TABLE dbo.YourTable ADD YourJSON nvarchar(MAX) NULL;
GO
ALTER TABLE dbo.YourTable ADD CONSTRAINT chk_YourTable_ValidJSON CHECK (ISJSON(YourJSON) = 1 OR YourJSON IS NULL);

SQL server has a JSON data type for this. SQL 服务器为此具有 JSON 数据类型。 This is wrong.这是错误的。

If your version doesn't, you can just store it as a string with VARCHAR or TEXT .如果您的版本没有,您可以将其存储为带有 VARCHAR或 TEXT的字符串。

This article reckons NVARCHAR(max) is the answer for documents greater than 8KB, for documents under that you can use NVARCHAR(4000) which apparently has better performance. 本文认为NVARCHAR(max)是大于 8KB 的文档的答案,对于在此范围内的文档,您可以使用NVARCHAR(4000)显然具有更好的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM