在DataReader的倍数表 [英] Multiples Table in DataReader
问题描述
我通常使用数据集
,因为它是非常灵活的。最近我分配code优化任务,减少点击到数据库中,我改变两个查询在一个过程。一个查询返回计数
和实际数据
其他收益。也就是说,我的存储过程
返回两个表。现在,我知道如何使用数据集
来阅读这两个表,但我需要使用的DataReader
来阅读这两个表。在搜索中,我发现这。
I normally used DataSet
because It is very flexible. Recently I am assigned code optimization task , To reduce hits to the database I am changing two queries in one procedure. one Query returns the count
and the other returns the actual data
. That is , My stored procedure
returns two tables. Now, I know how to read both tables using DataSets
, But I need to read both tables using DataReader
. In search of that I found This.
我按照文章,写我的code是这样的:
I follow the article and wrote my code like this:
dr = cmd.ExecuteReader();
while (dr.Read())
{
}
if (dr.NextResult()) // this line throws exception
{
while (dr.Read())
{
但我在dt.NextResult得到一个例外。例外情况是:
But I am getting an exception at dt.NextResult. Exception is :
Invalid attempt to call NextResult when reader is closed.
我也试图谷歌上面的错误,但仍然没有能够解决这个问题。
任何帮助将大大AP preciated。我需要使用读多个表的DataReader
,这可能吗?
I also attempted to Google above error , but still not able to solve the issue.
Any help will be much appreciated. I need to read multiple tables using datareader
, is this possible?
推荐答案
试试这个,因为这将关闭连接,数据读取器和命令一次任务克服,因此,这不会给DataReader的关闭异常
Try this because this will close connection ,data reader and command once task get over , so that this will not give datareader close exception
还做检查这样的如果(reader.NextResult())
来检查有下一个结果,
Also do check like this if(reader.NextResult())
to check there is next result,
using (SqlConnection connection = new SqlConnection("connection string here"))
{
using (SqlCommand command = new SqlCommand
("SELECT Column1 FROM Table1; SELECT Column2 FROM Table2", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show(reader.GetString(0), "Table1.Column1");
}
if(reader.NextResult())
{
while (reader.Read())
{
MessageBox.Show(reader.GetString(0), "Table2.Column2");
}
}
}
}
}
这篇关于在DataReader的倍数表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!