DataReader in ADO.NET
In ADO.NET, the DataReader
class is used to retrieve data in a forward-only, read-only manner from a data source. It provides a fast and efficient way to access data when you don't need to update or modify the data.
Here's an example of how you can use the DataReader
class in C#:
using System; using System.Data.SqlClient; class Program { static void Main() { string connectionString = "YourConnectionString"; string query = "SELECT * FROM Customers"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(query, connection); connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // Access data from the reader using the column index or column name int customerId = reader.GetInt32(0); string customerName = reader.GetString(1); string address = reader.GetString(2); Console.WriteLine($"Customer ID: {customerId}"); Console.WriteLine($"Customer Name: {customerName}"); Console.WriteLine($"Address: {address}"); Console.WriteLine(); } } } } }
In this example, we first create a SqlConnection
object with the appropriate connection string. Then, we create a SqlCommand
object with the SQL query we want to execute.
Inside the using
statement, we open the connection and execute the query using the ExecuteReader()
method, which returns a DataReader
object.
We then use a while
loop to iterate over the rows returned by the DataReader
. The Read()
method advances the reader to the next row. Inside the loop, we can access the values in each column of the current row using the appropriate Get
methods provided by the DataReader
(e.g., GetInt32
, GetString
, etc.), either by column index or column name.
Finally, we output the retrieved data to the console.
Remember to replace "YourConnectionString"
with the actual connection string for your database. Also, make sure to handle any exceptions that may occur during the execution of the code.