关闭Connection前检查一下有没有和它关联的DataReader没关闭,如何得到和它关联的DataReader?

解决方案 »

  1.   

    可以用:
    OleDbDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);
    关闭dr就自动关闭相应的connection
      

  2.   

    应该是自己保存这些 DataReader.
      

  3.   

    To:yezie(椰子),这种 方法不行,我查过Msdn,有些情况下不会自动关闭connection
    To vrace(干什么呢?在写程序!) ,我自己写了个类苦,实现数据库的操作,调用时都会保存Reader,使用完后把它关闭。但我担心有时会忘记关闭Reader,所以我想在这个类库里提供个检查 的方法,根据Connection得到和它关联的DataReader,检查是否关闭
      

  4.   

    参考
    http://community.csdn.net/Expert/TopicView.asp?id=3877118
      

  5.   

    其实是没有必要的,因为你的SqlDataReader是动态创建的,调用的时候可以采用以下方式确保SqlDataReader的关闭
    using(SqlDataReader dr = UDBClass.DataReader("select * from [tableName]")){}
    //通过using 来自动关闭dr
      

  6.   

    我只想关闭Reader并不想关掉Connection,:(
      

  7.   

    Connection只带缓存机制,不需要考虑,使用数据后马上关闭最好
      

  8.   

    Connection的缓存机制效率太差,数据访问量大时几乎不起作用
      

  9.   

    第一种:OleDbDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);
    关闭dr就自动关闭相应的connection第二种:
    在.net中操作sql server如何取得sql server的错误代码和信息?SqlConnection sqlConn = null;
    SqlCommand sqlCommand = null;
    try
    {
    sqlConn = new SqlConnection(@"server=(local);database=northwind;integrated security=sspi");
    sqlCommand = new SqlCommand("select * from customer", sqlConn);
    sqlConn.Open();
    SqlDataReader dr = sqlCommand.ExecuteReader();
    }
    catch (SqlException e)
    {
    Console.WriteLine(e.Message);
    }
    catch (Exception e)
    {
    Console.WriteLine(e.Message);
    }
    finally
    {
    if (sqlConn != null)
    {
    if (sqlConn.State != ConnectionState.Closed)
    sqlConn.Close();
    sqlConn.Dispose();
    }
    }第三种:
    SqlDataReader的关闭
    using(SqlDataReader dr = UDBClass.DataReader("select * from [tableName]")){}