using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); using (SqlDataReader reader = cmd.ExecuteReader()) { DataTable schemaTable = reader.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { Console.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"]); } } }
using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM Orders WHERE OrderDate > @date", conn); cmd.Parameters.AddWithValue("@date", DateTime.Now.AddDays(-7)); using (SqlDataReader reader = cmd.ExecuteReader()) { int orderIdColumnIndex = reader.GetOrdinal("OrderId"); int customerIdColumnIndex = reader.GetOrdinal("CustomerId"); while (reader.Read()) { int orderId = reader.GetInt32(orderIdColumnIndex); string customerId = reader.GetString(customerIdColumnIndex); Console.WriteLine("Order ID: " + orderId + ", Customer ID: " + customerId); } } }This code connects to a SQL Server database and executes a SELECT statement on the 'Orders' table, filtering by the 'OrderDate' column to only return orders from the last week. The SqlDataReader object's GetSchemaTable method is not used in this example but the GetOrdinal method is used to get the index of the 'OrderId' and 'CustomerId' columns. The code then uses the SqlDataReader object's GetInt32 and GetString methods to retrieve the values of these columns from each row in the ResultSet. The values are then written to the console. Package library: System.Data.SqlClient. This package is included in the .NET framework and does not need to be installed separately.