What would be the best way to avoid SQL injection on the C#.net platform.
Please post an C# implementation if you have any.
See Question&Answers more detail:osWhat would be the best way to avoid SQL injection on the C#.net platform.
Please post an C# implementation if you have any.
See Question&Answers more detail:osThere's no algorithm needed - just don't use string concatenation to build SQL statements. Use the SqlCommand.Parameters collection instead. This does all the necessary escaping of values (such as replacing '
with ''
) and ensures the command will be safe because somebody else (i.e. Microsoft) has done all the testing.
e.g. calling a stored procedure:
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand("MySprocName", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@Param1", param1Value);
return command.ExecuteReader();
}
This technique also works for inline SQL statements, e.g.
var sql = "SELECT * FROM MyTable WHERE MyColumn = @Param1";
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@Param1", param1Value);
return command.ExecuteReader();
}