Dzwebs.Net

撰写电脑技术杂文十余年

using与SqlDataReader之嵌套使用范例

Admin | 2016-3-18 9:24:21 | 被阅次数 | 9809

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

  如果在程序中,大量使用SqlDataReader对象的话,会导致连接池耗尽的情况发生。仍然,有些时候,我们又不得不使用多个SqlDataReader。

  因此,我们要解决的办法是,即要使用多个SqlDataReader,同时又不能让连接池耗尽,所以,我们得解决连接及时的关闭问题。

  下面为大家提供范例,如何使用这两者对象。

  using (SqlConnection Conn = new SqlConnection()) //第一个连接
  {
            Conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CoachExamOnlineStr"].ToString();
            Conn.Open();
            using (SqlCommand Cmd = Conn.CreateCommand())
            {
                Cmd.CommandText = MySqlStr;
                using (SqlDataReader MySqlReader = Cmd.ExecuteReader())  //
                {
                    while (MySqlReader.Read())
                    {

       using (SqlConnection Conn1 = new SqlConnection()) //第二个连接对象Conn1,因为如果沿用上面的Conn会导致SqlReader未关闭的错误提示
                        {
                            Conn1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CoachExamOnlineStr"].ToString();
                            Conn1.Open();
                            SqlCommand Cmd2 = Conn1.CreateCommand();
                            Cmd2.CommandText = "select ID,ExamName from GetToExamBase where ID=1" ;
                             (CheckAddResult(Cmd2)) //调用函数,传递的参数是SqlCommand对象
       }

      }

     }

   }

  }


该杂文来自: 数据库Sql,VFP,Access

上一篇:SQL中使用CHARINDEX查找

下一篇:多个sqldatareader嵌套的另类解决办法

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计