简体   繁体   English

为什么我的SQLDataReader只是从数据库表中读取最后一行?

[英]Why is my SQLDataReader just reading the last row from database table?

The same query works fine in SQL Server. 相同的查询在SQL Server中工作正常。 I need it to return all rows read from the DB table in c#. 我需要它来返回从c#中的数据库表读取的所有行。

SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = @"SELECT TypeName, Sum(HitNo) FROM TypeHit GROUP BY TypeName";

SqlDataReader sdr = cmd1.ExecuteReader();
sdr.Read();

if (sdr.HasRows)
{
   while (sdr.Read())
   {
       TextBox1.Text = sdr.GetString(0) +" at " + sdr.GetInt32(1);
   }
}

Why are you using sdr.Read() , that will advance the reader to the next block of data? 为什么使用sdr.Read() ,它将使阅读器前进到下一个数据块?

DataReader.Read Method DataReader.Read方法

You're also overwriting the TextBox '-Text property for every record in the reader since while (sdr.Read()) is a loop. 你还覆盖TextBox “ -文本属性每条记录中读取,因为while (sdr.Read())是一个循环。

using(SqlDataReader sdr = cmd1.ExecuteReader())
{
        if (sdr.HasRows)
        {
            while (sdr.Read())
            {
                TextBox1.Text += sdr.GetString(0) + " at " + sdr.GetInt32(1) + Environment.NewLine;
            }
        }
        else
        {
            TextBox1.Text = "No rows found.";
        }
}

Retrieving Data Using a DataReader (ADO.NET) 使用DataReader(ADO.NET)检索数据

You need to append result in loop: 您需要在循环中附加结果:

TextBox1.Text = TextBox1.Text+sdr.GetString(0) +" at " + sdr.GetInt32(1);

Also, from performance point of view, it's better to use StringBuilder : 另外,从性能角度来看,最好使用StringBuilder

StringBuilder bld = new StringBuilder();
if (sdr.HasRows)    
{    
   while (sdr.Read())    
   {    
      bld.Append(sdr.GetString(0));
      bld.Append(" at ");
      bld.Append(sdr.GetInt32(1));    
    }    
 }
 TextBox1.Text = bld.ToString();

In each loop you replace the last TextBox1.Text with the data fetched. 在每个循环中,将最后一个TextBox1.Text替换为获取的数据。
So you end up with only the last line. 因此,您只剩下最后一行。 If you need to see all the results you need something like this. 如果需要查看所有结果,则需要类似以下的内容。

   StringBuilder sb = new StringBuilder();
   while (sdr.Read()) 
   { 
       sp.AppendLine(sdr.GetString(0) +" at " + sdr.GetInt32(1)); 
   } 
   TextBox1.Text = sb.ToString();

also change the TextBox MultiLine property to True and resize the TextBox1 to show more than one line 还将TextBox MultiLine属性更改为True调整 TextBox1的大小以显示多行

ouch ... missed the bogus sdr.Read() before loop.... 哎呀...在循环之前错过了假的sdr.Read()。

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

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