阅读器关闭时尝试调用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);
}
以后一定会记住的。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步