首页 > 解决方案 > 从查询结果中保存 json 文档

问题描述

我正在使用下面的代码将 JSON 文档从 SQL 查询的结果保存到驱动器中。

该程序会生成一个空白的 |JSON 文档,但如果我将结果保存为.txtusing则SqlDataReader可以按预期工作。

C#:

string json = String.Empty;
string query = "SELECT TOP 10 [BusinessEntityID],[NationalIDNumber],[OrganizationNode],[OrganizationLevel] FROM [HumanResources].[Employee] FOR JSON AUTO";
string connectionSql = "Server=(local);Database=AdventureWorks2016CTP3;Integrated Security=true";
StreamWriter myFile = new StreamWriter(@"C:\temp\employee.json");
using (SqlConnection connection = new SqlConnection(connectionSql))
{
    SqlCommand command = new SqlCommand(query, connection);
    connection.Open();
    json = command.ExecuteScalar().ToString();
}

标签: c#json

解决方案


根据官方文档,您不应该使用ExecuteScalar来获取for json查询结果,ExecuteReader而是。

这是从文档中复制的代码示例:

var queryWithForJson = "SELECT ... FOR JSON";
var conn = new SqlConnection("<connection string>");
var cmd = new SqlCommand(queryWithForJson, conn);
conn.Open();
var jsonResult = new StringBuilder();
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
    jsonResult.Append("[]");
}
else
{
    while (reader.Read())
    {
        jsonResult.Append(reader.GetValue(0).ToString());
    }
}

注意:你应该使用usingfor 子句conn,因为它们cmdreader实现了IDisposable


推荐阅读