阅读器关闭时尝试调用Read无效时的解决方法

今天在写asp .netmvc的项目时,发现了个困扰我很久的问题,经过仔细研究终于解决了。
问题如下:
在这里插入图片描述首先来看一下原来有问题的代码:

 public static SqlDataReader Excutereader(string sql,params SqlParameter [] param) {
            using (SqlConnection conn = new SqlConnection(constr)) {
                SqlCommand cmd = new SqlCommand(sql,conn);
                PrepareCommand(conn,cmd,sql,param);
                return cmd.ExecuteReader();
            }
        }
        

在网上查了查都是说cmd.ExecuteReader();里面给个参数CommandBehavior.CloseConnection就可以了,结果我放上去之后还是不行,后来将using去掉才可以的,using的作用就是用完之后自动关闭连接,所有既然用了CommandBehavior.CloseConnection关闭连接就无需在用using了,所以去掉即可。下面是正确代码:

 //3.查询多条语句
        public static SqlDataReader ExcuterReader(string sql, params SqlParameter[] param)
        {
            SqlConnection conn = new SqlConnection(constr);

            SqlCommand cmd = new SqlCommand(sql, conn);
            Preparcommand(conn, cmd, sql, param);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);


        }

以后一定会记住的。

posted @ 2019-03-05 22:07  穆雄雄  阅读(408)  评论(0编辑  收藏  举报