gpt4 book ai didi

c# - SQL 阅读器多个结果不返回所有行

转载 作者:行者123 更新时间:2023-11-30 18:20:03 24 4
gpt4 key购买 nike

我从查询中获取多个结果并将它们写入 .CSV 文件。问题是查询返回 1700 行,但这段代码只将 1300 行写入文件。例如,我缺少 1301 到 1700 行。我想知道这段代码有什么问题:

using (SqlDataReader reader = exportCmd.ExecuteReader())
using (StreamWriter writer = new StreamWriter(exportFilename))
{
string Separator = ",";

while (reader.HasRows)
{
while (reader.Read())
{
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
{
if (columnCounter > 0)
{
writer.Write(Separator);
}

writer.Write(reader.GetValue(columnCounter).ToString());
}

writer.WriteLine(string.Empty);
}

reader.NextResult();
}

writer.Dispose();
}

提前致谢

最佳答案

您的一个结果没有返回任何行,这就是为什么您缺少行,外部 while (reader.HasRows) 退出而不检查下一个结果。

 using (SqlDataReader reader = exportCmd.ExecuteReader())
using (StreamWriter writer = new StreamWriter(exportFilename))
{
string Separator = ",";

while (reader.HasRows)
{
while(reader.Read())
{
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
{
if (columnCounter > 0)
{
writer.Write(Separator);
}

writer.Write(reader.GetValue(columnCounter).ToString());
}

writer.WriteLine(string.Empty);
}


While(reader.NextResult() && !reader.hasrows)
{
// might be a bette way to do this , problem is that one of your result has no rows, then it exits...
}

}

writer.Dispose();
}

关于c# - SQL 阅读器多个结果不返回所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37982566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com