加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么在调用SqlDataReader.NextResult后没有找到数据?

发布时间:2020-12-15 20:01:38 所属栏目:百科 来源:网络整理
导读:我的问题是这不起作用; while (reader.Read()){ if (reader.NextResult() == true) { json.AppendFormat("{{"AvgDate": "{0}"}},{{"MarkerID": "{1}"}},",reader["AvgDate"],reader["MarkerID"]); } 但这有效; while (reader.Read()){ json.AppendFo
我的问题是这不起作用;

while (reader.Read())
{
   if (reader.NextResult() == true)
   {
      json.AppendFormat("{{"AvgDate": "{0}"}},{{"MarkerID": "{1}"}},",reader["AvgDate"],reader["MarkerID"]);
   }

但这有效;

while (reader.Read())
{
    json.AppendFormat("{{"AvgDate": "{0}"}},reader["MarkerID"]);
}

第一个问题是读者没有找到任何要读取的数据.我明白了

“Invalid attempt to read when no data
is present.”

谁能明白为什么?

解决方法

NextResult()使读者前进到从查询返回的下一个结果集.你写它的方式,它将跳过第一个结果集(可能是唯一的结果集).

我认为你想要的模式是:

if (reader.HasRows)
{
     do
     {
        while (reader.Read())
        {
             ...
        }
     }
     while (reader.NextResult());
}

这将检查是否有任何结果,如果有,则读取每个结果集中的结果,直到没有剩余的结果为止.

编辑:根据评论:

对于JSON,请考虑使用临时对象列表,然后使用DataContractJsonSerializer:

public class DateClass
 {
      public string AvgDate { get; set; }
      public int MarkerID { get; set; }
 }

 ...

 var dates = new List<DateClass>();
 if (reader.HasRows)
 {
       while (reader.Read())
       {
           var date = new DateClass { AvgDate = reader["AvgDate"].ToString(),MarkerID = (int)reader["MarkerID"] };
            dates.Add( date );
       }
 }

 var stream = new MemoryStream();
 var serializer = new DataContractJsonSerializer( typeof(DateClass) );
 serializer.WriteObject( stream,dates );
 stream.Seek( 0,SeekOrigin.Begin );
 return stream.ToString();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读