using System.Data.SqlClient; string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"; string sqlQuery = "SELECT * FROM Customers"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(sqlQuery, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { string customerName = reader.GetString(1); Console.WriteLine("Customer Name: " + customerName); } }
using System.Data.SqlClient; string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"; string sqlQuery = "SELECT * FROM Orders"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(sqlQuery, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { int orderId = reader.GetInt32(reader.GetOrdinal("OrderID")); Console.WriteLine("Order ID: " + orderId); } }In this example, we are using the GetInt32 method to retrieve the OrderID column from the Orders table. The package library for the SqlDataReader class is the System.Data.SqlClient namespace. This namespace provides the required classes and methods to work with SQL Server databases in C#.