【问题标题】:Invalid attempt to call Read when reader is closed on while(Reader.read()). why?当阅读器在 while(Reader.read()) 上关闭时,调用 Read 的尝试无效。为什么?
【发布时间】:2016-01-06 06:37:22
【问题描述】:
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection("Data Source=NSIC;Initial Catalog=Dev;User ID=sa;Password=123456"))
{
    // SqlDataAdapter adapter = new SqlDataAdapter("Select * from Employee", connection);
    connection.Open();
    //adapter.Fill(ds);
    using (SqlCommand command = new SqlCommand("Select * from Employee", connection))
    {
        using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
        {
            while (reader.Read()) //Error is here
            {
                var table = new DataTable();
                table.Load(reader);
                ds.Tables.Add(table);
            }
        }
    }
}
GridView1.DataSource = ds;

我正在尝试从数据 sql server 中检索数据。但 while(Reader.read()) 出现错误。

阅读器关闭时调用 Read 的尝试无效 while(Reader.read()).

为什么?

【问题讨论】:

  • 尝试ExecuteReader 不带CloseConnection CommandBehavior。像这样command.ExecuteReader()
  • 你的读者可能是空的。在 while 循环之前测试 null。
  • 为什么要每行创建一个数据表?尝试简单地删除 while 部分,将 3 行留在里面。

标签: c#


【解决方案1】:

这里的问题是你在while循环中使用DataTable.Load

while 循环基本上说“虽然还有更多行”,然后您调用 DataTable.Load 加载 所有行,然后返回检查更多行。

相反,您可以简单地完全删除 while 循环:

using (SqlDataReader reader = command.ExecuteReader()) 
{
    var table = new DataTable();
    table.Load(reader);
    ds.Tables.Add(table);
}

【讨论】:

    【解决方案2】:

    我认为使用CommandBehavior.CloseConnection 会惹恼你的读者。

    尝试像下面这样使用它;

        using (SqlConnection connection = new SqlConnection("Data Source=NSIC;Initial Catalog=Dev;User ID=sa;Password=123456"))
        using (SqlCommand command = new SqlCommand("Select * from Employee", connection))
        {
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader()) 
            {
                while (reader.Read())
                {
                   var table = new DataTable();
                   table.Load(reader);
                   ds.Tables.Add(table);
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多