query sql server with parameters in csharp

Here is an example C# code snippet to query SQL Server with parameters using ADO.NET:

main.cs
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand("SELECT * FROM Customers WHERE City=@city", connection);
    command.Parameters.Add("@city", SqlDbType.NVarChar).Value = "London";

    connection.Open();

    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        Console.WriteLine("{0}\t{1}\t{2}", reader["CustomerID"], reader["CompanyName"], reader["ContactName"]);
    }
}
474 chars
15 lines

In this example, we are selecting all customers from the "Customers" table where the "City" column equals "London". We are using a parameterized query to prevent SQL injection attacks. The "@city" parameter is defined in the SQL command string, and its value is set using the "command.Parameters.Add" method, which also specifies the data type of the parameter. Finally, we execute the query using the "command.ExecuteReader" method and loop through the results using a SqlDataReader object.

gistlibby LogSnag