C# 如何使 sqlDataReader 脱机?
由于未正确关闭连接,出现内存泄漏。这是由于使用全局函数访问数据库(使用不同的sql字符串),但我传回了sqldatareader。 我无法在方法中关闭它,也无法关闭与数据库的连接,因为它关闭了对数据的访问!并且它无法从该方法外部正确关闭。 :(
有什么方法可以获取 sqldatareader 授予离线访问权限的所需表。 这样我就可以关闭所有连接,但仍然可以访问该表。
注意,会返回不同的表所以存在不同的字段。我不想每次尝试连接时都必须重复代码,
private SqlDataReader OpenDataStream(String sql)
{
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = new SqlConnection();
sqlComm.Connection.ConnectionString = @"Myconnectionstring";
sqlComm.CommandText = sql;
sqlComm.Connection.Open();
SqlDataReader data = null;
data = sqlComm.ExecuteReader();
return data;
// Closing data here, or connection, results in returned object inaccessable.
}
或者可能是在方法之外关闭所有内容的有效工作方式(在访问了我需要的内容之后)?
I have a memory leak, due to not closing the connection properly. This is due to using a global function to access the database (with different sql strings), but I pass back an sqldatareader. I cant close this in the method, nor the connection to the DB, as it closes access to the data! And it doesnt close properly from outside this method. :(
Is there Anyway way I can take the desired table, that the sqldatareader grants access to, offline. So that I can close all the connections, but still access the table.
Note, Different tables are returned so different fields exist. I dont want to have to duplicate code each time I try and connect.
private SqlDataReader OpenDataStream(String sql)
{
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = new SqlConnection();
sqlComm.Connection.ConnectionString = @"Myconnectionstring";
sqlComm.CommandText = sql;
sqlComm.Connection.Open();
SqlDataReader data = null;
data = sqlComm.ExecuteReader();
return data;
// Closing data here, or connection, results in returned object inaccessable.
}
or maybe a valid working way of closing it all down outside the method (after I have accessed what I need)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试 DataTable.Load Method 方法:
Try the DataTable.Load Method method:
您可以只返回
DataTable
而不是SqlDataReader
。这将用您的数据填充表,并且您可以在方法结束执行之前关闭连接。本文可能值得一读。
You could just return a
DataTable
instead of aSqlDataReader
. This will fill the table with your data and you can close the connections before the method ends its execution.This might be worth a read.
不要返回读取器,而是返回填充的
DataTable
。Don't return the reader, return a populated
DataTable
instead.您可以考虑使用诸如
DataSet
之类的东西来提供对数据的离线访问。这里有一些示例 - http://msdn.microsoft.com/en-us/ library/ms971499.aspx或
此问题提供了多种从数据读取器中取出数据并将其存储在内存中的方法 - 如何轻松将 DataReader 转换为 List?
You could consider using using something like a
DataSet
that provides off-line access to your data. Some examples here - http://msdn.microsoft.com/en-us/library/ms971499.aspxor
This question provides a number of methods for taking the data out of a datareader and storing it in memory - How can I easily convert DataReader to List<T>?