已经是一个与此命令关联的开放DataReader,必须先关闭它

时间:2013-04-23 06:48:21

标签: c#

当我尝试执行代码时,它显示上述错误。

try
{
    com.CommandText = "select * from Export";
    com.ExecuteReader();

    data_mode = "Export";
    com.CommandText = "Insert INTO [" + New_access_file + "]." + data_mode + " select * FROM ExportDATA";
    com.ExecuteNonQuery();
}
catch
{
    data_mode = "Export";
    com.CommandText = "SELECT * INTO [" + New_access_file + "]." + data_mode + " FROM ExportDATA";
    com.ExecuteReader();
}

2 个答案:

答案 0 :(得分:3)

完成使用DataReader对象后,应始终调用Close方法。

请注意,当DataReader打开时,Connection仅由该DataReader使用。在原始DataReader关闭之前,您无法为Connection执行任何命令,包括创建另一个DataReader。

使用此代码,

var reader = com.ExecuteReader();
//do whatever with reader

reader.Close();

您可以使用CommandBehavior.CloseConnection获取更多信息Will ExecuteReader(CommandBehavior.CloseConnection) always close connection?。我们可以使用它与Command对象的ExecuteReader方法一样传递它,如

var reader = com.ExecuteReader(CommandBehavior.CloseConnection);

这将确保当我们调用reader.Close()时,关联的连接对象也将被关闭。

答案 1 :(得分:0)

您需要一个开放式连接: -

try
                {   
                    con.open();

                    com.CommandText = "select * from Export";
                    com.ExecuteReader();

                    data_mode = "Export";
                    com.CommandText = "Insert INTO [" + New_access_file + "]." + data_mode + " select * FROM ExportDATA";
                    com.ExecuteNonQuery();
                }
                catch
                {
                    data_mode = "Export";
                    com.CommandText = "SELECT * INTO [" + New_access_file + "]." + data_mode + " FROM ExportDATA";
                    com.ExecuteReader();
                }
                 Finally
                 {
                   con.close();
                 }