【问题标题】:DataReader does not return data but the number of rowsDataReader 不返回数据而是返回行数
【发布时间】:2020-06-29 13:48:40
【问题描述】:

我有这个代码

string query = "SELECT * FROM table;"

try
{
   using (SqlConnection connection = new SqlConnection(this.ConnectionString))
   {
      connection.Open();

      using (SqlCommand cmd = new SqlCommand(query, connection))
      {
         SqlDataReader reader = cmd.ExecuteReader();
      }

      connection.Close();
   }
}

在阅读器中,我收到表中的行数,但没有数据。我在哪里迷路了?

【问题讨论】:

  • 你需要遍历阅读器(while (reader.Read())...)

标签: c# sqldatareader


【解决方案1】:

一旦你调用了ExecuteReader,你需要遍历它,读取每一行:

while(reader.Read())
{
  // Process the row...
}

另外,将阅读器放入using 块中是一种很好的做法:

using(SqlDataReader reader = cmd.ExecuteReader())
{
  while(reader.Read())
  {
    // Process the row
  }
}

【讨论】:

  • 好答案,当您添加一些示例代码如何访问单行及其数据时会更有帮助。
【解决方案2】:

你需要阅读阅读器

https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-data-using-a-datareader#:~:text=To%20retrieve%20data%20using%20a,rows%20from%20a%20data%20source.

SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
    while (reader.Read())
    {
           // 
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2020-04-11
    • 2011-07-24
    • 2020-06-29
    • 2021-01-13
    • 1970-01-01
    • 2021-03-17
    相关资源
    最近更新 更多