Wednesday, October 03, 2007

C# SqlCommand

Dynamic SQL queries in ADO.Net. How to bind dynamic parameters to a query and avoid concatenating strings. Avoiding problems with cross site scripting attacks. Good link SqlCommand bind parameter info.

SqlCommand cmd = new SqlCommand( @"SELECT something, anothervalue FROM sometable WHERE something > @param1 AND anothervalue > @param2" );

cmd.Parameters.AddWithValue("@param1", "2007-10-02");
cmd.Parameters.AddWithValue("@param2", 5678 );

SqlDataReader reader = cmd.ExecuteReader();
while ( reader.Read() ){
Console.WriteLine( reader["something"].ToString() );

No comments: