Kamiran
Kamiran

Reputation: 155

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.

Upvotes: 1

Views: 77

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

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?

Upvotes: 3

puko
puko

Reputation: 2970

Only first, its prevent to sql injection.

http://www.c-sharpcorner.com/UploadFile/puranindia/parameterized-query-and-sql-injection-attacks/

Upvotes: 0

Related Questions