What is ADO.NET?What are the key components of ADO.NET?What are the ADO.NET namespaces?What is the meaning of object pooling?What are the differences between ADO.NET and classic ADO?Explain the architecture of ADO.NET.?What is a Connection String in ADO.NET C#??How do you establish a database connection using ADO.NET?Explain the concept of Connection Pooling in ADO.NET C#.Differentiate between Object pooling and Connection pooling in C#?What is a DataReader in ADO.NET? Explain with C# example?What is the functionality of CommandBehavior.SchemaOnly?Why CommandBehavior.SingleResult flag is used in ADO.NET?What does CommandBehavior.SingleRow do in ADO.NET?How we can get multiple results by DataReader using same connection in C#?How can we force the connection object to close after my DataReader is closed?What is a DataSet in ADO.NET? Explain with C# example?What are typed and un-typed datasets in ADO.NET C#?Write down some of the characteristic of DataSet?What is the difference between dataSet and DataReader?Why is DataSet Slower than DataReader? Explain with Example.How does DataSet handle data in a disconnected environment?What is the Difference between connected and disconnected architectire?Explain HasChanges() method of DataSet in C#.Explain GetChanges() method with detaild C# Example.Explain RejectChanges() method with C# Example.Explain AcceptChanges() method with C# Example.What are the various methods provided by DataSet for XML in C#?What is the purpose of DataAdapter in ADO.NET?Explain the steps involved in retrieving data using DataAdapter.

Retrieving Multiple Result Sets with DataReader in C#

In C#, you can use the DataReader to retrieve multiple result sets from the same database connection by utilizing the NextResult() method. This allows you to execute a SQL query that returns multiple result sets and access each of them sequentially. Below is an explanation along with a complete source code example and the expected output:

Explanation

  1. Open Connection: First, establish a connection to your database using the SqlConnection class. This connection serves as a link to your database.
  2. Execute SQL Query: Create a SqlCommand and execute a SQL query that returns multiple result sets. Ensure that your query contains multiple SELECT statements, each representing a separate result set.
  3. DataReader Initialization: Use the ExecuteReader() method of the SqlCommand to create a DataReader. The DataReader allows you to iterate through the rows of the first result set.
  4. Iterate Through First Result Set: Use a while loop to read and process the rows of the first result set using the DataReader.
  5. Access Subsequent Result Sets: To access subsequent result sets, call the NextResult() method of the DataReader. This method advances the DataReader to the next result set if one exists. You can use this method in a loop to access all the result sets.

Sample Code


using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        // Define the connection string to your database
        string connectionString = "Data Source=SQlServerName;Initial Catalog=DbName;user id = youruserid; password = yourpassword";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                // Open the connection
                connection.Open();

                // Create a SqlCommand with a query that returns multiple result sets
                string query = "SELECT * FROM Customers; SELECT * FROM Orders";
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    // Create a DataReader to read the first result set
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        // Read and process the first result set
                        Console.WriteLine("First Result Set (Customers):");
                        while (reader.Read())
                        {
                            Console.WriteLine($"{reader["CustomerID"]} - {reader["ContactName"]}");
                        }

                        // Move to the next result set
                        reader.NextResult();

                        // Read and process the second result set
                        Console.WriteLine("\nSecond Result Set (Orders):");
                        while (reader.Read())
                        {
                            Console.WriteLine($"{reader["OrderID"]} - {reader["OrderDate"]}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
}

Expected Output

In this example, we execute a SQL query that returns data from both the "Customers" and "Orders" tables. Here's the expected output:


First Result Set (Customers):
ALFKI - Maria Anders
ANATR - Ana Trujillo
...

Second Result Set (Orders):
10248 - 1996-07-04 00:00:00
10249 - 1996-07-05 00:00:00
...

As you can see, we retrieve and display data from two different result sets within the same connection using the DataReader. The NextResult() method allows us to move from one result set to another sequentially.