using System.Data.SqlClient; SqlConnection conn = new SqlConnection(myConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM myTable", conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["ColumnName"]); } conn.Close();
using System.Data.SqlClient; SqlConnection conn = new SqlConnection(myConnectionString); conn.Open(); string cityName = "New York"; SqlCommand cmd = new SqlCommand("SELECT * FROM myTable WHERE CityName = @cityName", conn); cmd.Parameters.AddWithValue("@cityName", cityName); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["ColumnName"]); } conn.Close();In this example, we use a parameterized SQL statement to retrieve data from a database. We first create a SqlConnection object and open the connection. Then, we create a SqlCommand object with a SQL SELECT statement that includes a parameter. We use the AddWithValue method to set the value of the parameter and execute the command. Finally, we loop through the data using the SqlDataReader object and print out the values of each row. The package library for the System.Data.SqlClient SqlCommand class is part of the .NET Framework.