Read Operation using SqlClient

The Read operation retrieves records from a database. This example demonstrates reading employee records using SqlDataReader.

Key Topics

Select Example

Example

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=MyDatabase;User Id=myUser;Password=myPassword;";
        string query = "SELECT Name, Department FROM Employees";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(query, connection);

            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Console.WriteLine("Name: " + reader["Name"] + ", Department: " + reader["Department"]);
                }
            }
        }
    }
}

Explanation: This example uses SqlDataReader to execute a SELECT statement and iterate through the results.

Key Takeaways

  • Use ExecuteReader to retrieve data in a forward-only, read-only manner.
  • Iterate through the results using Read() method of SqlDataReader.