Yogev
Yogev

Reputation: 141

SQL injection, using Parameterised Queries

I have some questions about how to prevent sql injectiion with the help of parameterised queries

sqlQuery="SELECT * FROM usersTbl WHERE username=@uname AND password=@passwd";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);

SqlParameter[] par = new MySqlParameter[2];

par[0] = new SqlParameter("@uname ", SqlDbType.VarChar,25);
par[1] = new SqlParameter("@passwd", SqlDbType.VarChar, 45);

And then I attach them to the SqlCommand and ExecuteScalar it.

For example the client insert the string ;DROP -- in the password variable, will the parameterised query prevent the DROP query to be executed ?

Thank you

Upvotes: 0

Views: 204

Answers (2)

John Woo
John Woo

Reputation: 263693

Of course, when the client pass ';DROP -- value in the password field, this will be parsed into

SELECT * 
FROM usersTbl 
WHERE username=@uname AND password=''';DROP --'

The command object will automatically escapes any single quotes found on the value.

UPDATE 1

As, I already told you, it won't. Because the quotes will be escaped by doubling the quotes. Example,

string pass_val = "'; DROP usersTbl;--";

when you passed that into command and its value is parameterized, this will become

SELECT * FROM usersTbl WHERE ... AND password='''; DROP usersTbl;--'

and NOT

SELECT * FROM usersTbl WHERE ... AND password=''; DROP usersTbl;--

Upvotes: 4

Chad
Chad

Reputation: 7507

Yes, the parameterized query will correctly escape any characters that would allow this to happen.

Upvotes: 1

Related Questions