c# - 从查询结果中保存 json 文档
问题描述
我正在使用下面的代码将 JSON 文档从 SQL 查询的结果保存到驱动器中。
该程序会生成一个空白的 |JSON 文档,但如果我将结果保存为.txt
using则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();
}
解决方案
根据官方文档,您不应该使用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());
}
}
注意:你应该使用using
for 子句conn
,因为它们cmd
都reader
实现了IDisposable
推荐阅读
- java - 对数据库会话上下文的更改通过池连接重用持续存在
- javascript - fullcalendar v5 - 单击 daygrid 顶部的图标时打开模式
- r - 如何去除异常值但保留 NA
- javascript - 如何在不更改内容的情况下更改日期的时区?
- c# - 何时使用 Xamarin 绑定而不是将对象传递给页面构造函数?
- json - 如何解析 twilio 通知 API 请求响应
- php - 如何在 PHP MySql 中根据用户角色检索数据
- mongodb - 从 MongoDB 中的文档数组创建字符串数组
- azure - 订购时 Azure Function Service Bus 触发器是必不可少的吗?
- c++ - 使用 QWidget::event 覆盖小部件中的 Tab 按