Datareader Error:读取器关闭时无效尝试调用Read。 [英] Datareader Error: Invalid attempt to call Read when reader is closed.

查看:87
本文介绍了Datareader Error:读取器关闭时无效尝试调用Read。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,



我使用datareader.read()方法创建了一个只从db读取数据的函数。它给了我错误:读取器关闭时无效尝试调用Read。



我的代码片段如下:



  public   int  ReturnInt( string  str)
{
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
cmd = new SqlCommand(str,con);
rd = cmd.ExecuteReader();
if (rd.Read())
{
return (Convert.ToInt32(rd [ 0 ]));
}
}
catch {}
最后 {con.Close();}
return 0 ;
}

私有 void Form_Load( object sender,EventArgs e)
{
ReturnInt( 从表名中选择计数(*)
}





错误发生在rd.Read( )。



告诉我为什么会出现这个错误以及解决方案是什么。



谢谢&安培;此致,

Sonal Patel

解决方案

请循环阅读。请确保不要关闭阅读器。

  while (rd.Read())
{
int val =(Convert.ToInt32(rd [ 0 ]));
}







希望这有帮助。


一些积分

  1. 使用 Int32.TryParse [ ^ ]
  2. 不是计算所有列(*),而是计算时间,尝试计算身份行(首选)以便快速执行,如下所示。

     选择计数( ID 来自 tablename 

  3. 当您使用 DataReader 时,您需要在循环时使用如下所示。

    参考 - 使用DataReader检索数据 [< a href =http://msdn.microsoft.com/en-us/library/haa3afyz.aspxtarget =_ blanktitle =New Window> ^ ]

      int  value =  0 ; 

    while (rd.HasRows)
    {
    while (rd。 Read ())
    {
    Int32.TryParse(rd [ 0 ],out value);
    }
    }

    返回值;


Hello friends,

I have made one function to just read data from db using datareader.read() method. It gives me error: "Invalid attempt to call Read when reader is closed."

My code snippet as below:

public int ReturnInt(string str)
{
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
cmd = new SqlCommand(str, con);
rd = cmd.ExecuteReader();
if (rd.Read())
{
return (Convert.ToInt32(rd[0]));
}
}
catch{}
finally{con.Close();}
return 0;
}

private void Form_Load(object sender, EventArgs e)
{
ReturnInt("select count(*) from tablename")
}



Error is coming on rd.Read().

Tell me why this error is generating and what is the solution for that.

Thanks & Regards,
Sonal Patel

解决方案

Please loop through the reader.Please make sure that don't close the reader.

 while (rd.Read())
{
int val= (Convert.ToInt32(rd[0]));
}




Hope this helps.


Some Points

  1. Use Int32.TryParse[^]
  2. Instead of counting all columns ("*"), which is time taking, try to count the identity row (preferred) for quick execution like below.

    select count(ID) from tablename

  3. When you are using DataReader, you need to use while loops like below.
    Refer - Retrieving Data Using a DataReader[^]

    int value = 0;
    
    while (rd.HasRows)
    {
        while (rd.Read())
        {       
            Int32.TryParse(rd[0], out value);
        }
    }
    
    return value;


这篇关于Datareader Error:读取器关闭时无效尝试调用Read。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆