There'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();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…