using语句下使用SqlDataReader异常:Invalid attempt to Read when reader is closed
来源:互联网 发布:衣服数据参考 编辑:程序博客网 时间:2024/06/02 03:06
学习.NET已经一周多了,这几天学习了一下MVC分层开发,就想封装一个获取SqlDataReader的工具类。但是在实际操作过程中却发生了异常。首先了解一下using语句,如果用using{}将代码块包起来,那么using中定义的连接信息,最后不用手动进行Close,会自动关闭,释放资源。
封装的工具类中的代码如下:
public static SqlDataReader GetDataReader(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connstr)) { SqlCommand cmd = new SqlCommand(sql, conn); foreach (SqlParameter parameter in parameters) { cmd.Parameters.Add(parameter); } try { conn.Open(); SqlDataReader sdr = cmd.ExecuteReader(); return sdr; } catch (Exception e) { throw; } } }
工具类在使用时,调用GetDataReader方法报错:“Invalid attempt to Read when reader is closed”。大概意思就是当reader关闭的时候,无法进行阅读。
查阅了一些资料以后,了解了原因:
using{}中代码执行完之后,连接自动关闭,而Reader与DataSet不同,DataSet已经将数据保存在本地内存中,而Reader并没有将数据保存在本地内存中,可以理解成只是指向了数据,连接关闭后用reader读取数据当然无法实现。
于是为了避免产生这种情况,我改用DataSet进行了工具类的封装,详细请见另一篇博客:
http://blog.csdn.net/datoubangzhu/article/details/78474138
阅读全文
1 0
- using语句下使用SqlDataReader异常:Invalid attempt to Read when reader is closed
- Do streams have to be closed when using popen
- When An SO is closed ,how to cancel it
- 第十五章 SqlDataReader reader = comm.ExecuteReader(); while (reader.Read())
- How to correctly read data when using epoll_wait
- SQLite 异常java.lang.IllegalStateException: attempt to re-open an already-closed object
- InnoDB is limited to row-logging when transaction isolation level is READ COMMITTED or READ UNCOMMIT
- Invalid state, the Connection object is closed.
- ExtJS4 reader.read is not a function
- oracle中merge into..using..on..when..when..用法 使用一条语句实现update/insert 语句
- android SQLiteDatabase attempt to re-open an already-closed object:
- IllegalStateException: attempt to re-open an already-closed object 错误
- Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream
- sqldatareader.reader()的问题
- hbase windowns 下, Will not attempt to authenticate using SASL (无法定位登录配置)
- Read Notify is the fastest, easiest, most reliable way to find out when email you've sent gets read.
- The installer cannot read the mwinstall.dll file, This is probably due to a CD reader which can.....
- The attempt to create vdi is failed
- 二叉树
- error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.32/info: open //./pipe/docker_eng
- 运算符(除法)
- CentOS设置IP
- [译文]Android架构组件-App架构指南
- using语句下使用SqlDataReader异常:Invalid attempt to Read when reader is closed
- 内置锁(三)---- synchronized的几个要注意的对象监视器
- mysql常规命令
- VTK 7.1.0+window7_64位+QT5.5配置及第一个实例运行
- java开发遇到的简单问题
- 二叉树的顺序存储实现及遍历
- 【uva-124】Following Orders (拓扑排序)竟然自己写出了全排列的算法!
- 18届清华硕士收割18家互联网sp offer总结
- Python---思维导图