Does using parameterized SqlCommand make my program immune to SQL injection?

sharptooth picture sharptooth · Aug 24, 2011 · Viewed 14.7k times · Source

I'm aware that SQL injection is rather dangerous. Now in my C# code I compose parameterized queries with SqlCommand class:

SqlCommand command = ...;
command.CommandText = "SELECT * FROM Jobs WHERE JobId = @JobId;";
command.Parameters.Add("@JobId", SqlDbType.UniqueIdentifier ).Value = actualGuid;
command.ExecuteNonQuery();

Will this automatically make my code immune to SQL injection? Do I have to do something extra?

Answer

Christian.K picture Christian.K · Aug 24, 2011

I'd say for your particular, and probably canonical, example for parametrized queries, yes it is sufficient.

However, people sometimes write code like this

cmd.CommandText = string.Format("SELECT * FROM {0} WHERE col = @col;", tableName);
cmd.Parameters.Add("@col", ...);

because there is simply no way to pass the tablename itself as a parameter and the desire to do exists sometimes - misguided or not. It seems it is then often overlooked, that tableName (unless maybe only read from a set of static/constant values that do not derive from any input) indeed allows for SQL injection.