C# - DataReader无法返回多个结果集

Goo*_*all 1 c# sqldatareader

我想要做的是类似于OP在这里问的:

DataReader中的Multiples表

我试图将一个或多个SQL查询的结果存储到单独的DataTables中.上述问题方法的问题在于它仅适用于每个结果集中的离散值.最好使用DataTables Load(reader)方法将每个结果集存储在单个语句中,而不是迭代所有DataReader的列.

在下面的代码中,我有两个SQL查询(尽管这应该适用于任意数量的查询),其结果我尝试存储在临时数据表中,然后存储到数据表列表中.我的代码的问题是它只返回第一个查询的结果集,并添加后续查询会抛出一个Reader is closed exception.

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        using (SqlCommand command = new SqlCommand
               ("SELECT TOP 10 Column1, Column2 FROM Table1; SELECT TOP 10 Column1, Column2 FROM Table2", connection))
        {
            connection.Open();

            using (SqlDataReader reader = command.ExecuteReader())
            {
                    while (reader.Read())
                    {
                        tempTable.Reset();
                        tempTable.Load(reader);
                        dataTables.Add(tempTable);
                    }

                    if (reader.NextResult())
                    {
                        while (reader.Read())
                        {
                            tempTable.Reset();
                            tempTable.Load(reader);
                            dataTables.Add(tempTable);
                        }
                    }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我已经挣扎了几个小时.我不确定DataTable/DataReader是否只是为我的用例设计得很差,或者我是否遗漏了一些基本的东西.

Goo*_*all 5

DataReader不适合我的需求,它的使用会产生冗长的代码,所以我使用了Daniel Kelly建议的DataAdapter.读取多个结果集的代码现在相对简单:

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        using (SqlCommand command = new SqlCommand
               ("SELECT TOP 10 Name, [Description] FROM Business; SELECT TOP 10 ConnectionId FROM Connection;SELECT TOP 10 Name FROM Business", connection))
        {
            connection.Open();

                SqlDataAdapter adapter = new SqlDataAdapter(command);
                DataSet set = new DataSet(); 
                adapter.SelectCommand = command;

                //Note here, that the adapter will create multiple tables for each result set
                adapter.Fill(set); 

                foreach (DataTable t in set.Tables)
                {
                    dataTables.Add(t);
                }

                dataTables.Add(tempTable);
        }
    } 
Run Code Online (Sandbox Code Playgroud)

阅读完你的评论后,我发现我对reader.Read()和NextResult()的理解是有缺陷的.此外,每次调用DataReader的加载方法时,读取器的连接都将被关闭.

感谢大家的意见和建议.我不会接受我自己的答案,因为那样会自负.