当我从sqldatareader读取数据时出现错误“读取器关闭时无法尝试调用Read”。 我的代码如下sqldatareader错误“当阅读器关闭时,尝试调用Read无效。”
显然这是由using语句在ExecSqlDataReader越来越封闭
我希望能够调用该方法,然后读者使用另一个类中,有没有什么办法解决这而不必循环ExecSqlDataReader方法中的SqlDataReader?
希望是有道理的
感谢
代码:
SqlDataReader reader = data.ExecSqlDataReader(1);
while (reader.Read())
{
.....
}
public SqlDataReader ExecSqlDataReader(int queryType = 0)
{
using (var conn = new SqlConnection(this.ConnectionString))
{
try
{
PrepareCommandForExecution(conn, queryType);
return _cmd.ExecuteReader();
}
finally
{
_cmd.Connection.Close();
}
}
}
private SqlCommand PrepareCommandForExecution(SqlConnection conn, int sqlType = 0)
{
_cmd.Connection = conn;
switch (sqlType)
{
case 0:
_cmd.CommandType = CommandType.StoredProcedure;
break;
case 1:
_cmd.CommandType = CommandType.Text;
_cmd.CommandText = _tSqltext;
break;
case 2:
_cmd.CommandType = CommandType.TableDirect;
break;
}
_cmd.CommandTimeout = this.CommandTimeout;
_cmd.Connection.Open();
return _cmd;
}
您正在关闭连接。而已。期。连接已关闭。您无法关闭连接,然后从中读取。它已关闭! –