zoukankan      html  css  js  c++  java
  • 在使用datareader结束时,要保证connection关闭

    使用CommandBehavior.CloseConnection来保证在关闭Datareader时,也关闭connection

    public static SqlDataReader(.....)

    {
                SqlCommand cmd = new SqlCommand();
                SqlConnection conn = new SqlConnection(connectionString);

                // we use a try/catch here because if the method throws an exception we want to
                // close the connection throw code, because no datareader will exist, hence the
                // commandBehaviour.CloseConnection will not work
                try
                {
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                    SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    cmd.Parameters.Clear();
                    return sdr;
                }
                catch
                {
                    conn.Close();
                    throw;
                }

    }

    在其它地主使用的方法,利用using

    using (SqlDataReader sdr = SQLHelper.ExecuteReader(SQLHelper.SQLConnString, CommandType.Text, SQL_Search_ById, adminParms))
                {
                    while (sdr.Read())
                    {
                        admin = new AdminInfo(sdr.GetInt32(0), sdr.GetString(1), sdr.GetString(2));
                    }
                }

    或者

    SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlSelect.ToString(), parms);
       while(dr.Read()) {
        usernames.Add(dr.GetString(0));
       }

       dr.Close();

    //一定要保证,使用之后的状态是关闭的。

  • 相关阅读:
    NET(C#)接入Dubbo服务,Zookeeper作为Dubbo服务的注册中心,实现thrift协议访问接口(3)
    zend studio快捷键
    Guid的生成和数据修整(去除空格和小写字符)
    工作中常用Windows快捷键整理(1)-快速关闭网页
    PHP学习笔记(3)-Zend Studio安装和汉化
    PHP学习笔记(2)
    PHP学习笔记(1)
    判断本机ip是电信还是网通
    作业 4/1
    logging 模块
  • 原文地址:https://www.cnblogs.com/wenming205/p/1401681.html
Copyright © 2011-2022 走看看