using System.Data.SqlClient; SqlConnection sqlConnection = new SqlConnection(connectionString); sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand("SELECT * FROM Products", sqlConnection); SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); while (sqlDataReader.Read()) { int productId = sqlDataReader.GetValue(0); string productName = sqlDataReader.GetValue(1).ToString(); decimal productPrice = sqlDataReader.GetValue(2); Console.WriteLine($"Product ID: {productId}, Name: {productName}, Price: {productPrice}"); } sqlReader.Close(); sqlConnection.Close();
using System.Data.SqlClient; SqlConnection sqlConnection = new SqlConnection(connectionString); sqlConnection.Open(); string query = "SELECT COUNT(*) FROM Employees"; SqlCommand sqlCommand = new SqlCommand(query, sqlConnection); int numberOfEmployees = (int)sqlCommand.ExecuteScalar(); Console.WriteLine($"Number of Employees: {numberOfEmployees}");In this example, we retrieve the number of rows in the Employees table using the ExecuteScalar() method, which executes the specified query and returns the first column of the first row in the result set. The SqlDataReader class and the GetValue() method are part of the System.Data.SqlClient namespace, which is part of the .NET Framework Class Library.