Search code examples
c#asp.netsql-injection

Which statement is better and more secure for SQL Injection?


Which statement is better and more secure to prevent any sql injection, or are they the same?

com.CommandText = "update tblTableName set Name=@name, Age=@age WHERE ID=1";
com.Parameters.AddWithValue("@name", name.ToString());
com.Parameters.AddWithValue("@age", age.ToString());

OR

com.CommandText = @"update tblTableName set Name=" + name.ToString() + ", Age=" + age.ToString() + " WHERE ID=1";

OR

com.CommandText = "update tblTableName set Name=" + HttpUtility.HtmlEncode(name.ToString()) + ", Age=" + age.ToString() + " WHERE ID=1";

OR is there a better way.? appriciate your help and opinion.


Solution

  • Only first one prevents SQL Injection attacks.

    You don't use any prepared statements and parameterized sql in your second or third example. I can send them 18; DROP TABLE tblTableName in your age variable. Creating html-encoded string with HttpUtility.HtmlEncode method doesn't help either.

    Also don't use AddWithValue method. It may generate unexpected results sometimes. Use .Add() method overloads to specify your column type and size explicitly.

    Read: Can we stop using AddWithValue() already?