Prevent SQL Script Injection

  • Thread starter Thread starter Johnny Luner
  • Start date Start date
J

Johnny Luner

I read an article about SQL Script Injection, it teaches me how to prevent
it using old fashion ASP:

String: p_strUsername = Replace(Request.Form("txtUsername"), "'", "''")
INT: p_lngID = CLng(Request("ID"))

How about C# in .NET? Any suggestions?

Thanks.
 
Johnny,

In .NET, the best way to protect against this is to create parameterized
queries and then set the values for the parameters. The connection, when
issuing the command, will handle the conversion of strings so that the
appropriate characters are escaped and injection attacks are prevented.

Hope this helps.
 
Thats a good method in classic ASP, however in .NET, you'll want to use parameterized query's or stored procedures.

Parameterized Queries look like:

string query = "select * from Users where UserName=@userName"

And then you add SqlParameters (or a form of Parameter) to the command object:

SqlCommand cmd = new SqlCommand(conn);
cmd.Parameters.Add(new SqlParameter("@username", txtUsename.Text))

You can find more info on the web about this & using stored procedures. However, this is the recommended way of avoiding (or rather, minimizing) the impact of sql injection.

Matt Hawley, MCAD .NET
http://www.eworldui.net

I read an article about SQL Script Injection, it teaches me how to prevent
it using old fashion ASP:

String: p_strUsername = Replace(Request.Form("txtUsername"), "'", "''")
INT: p_lngID = CLng(Request("ID"))

How about C# in .NET? Any suggestions?

Thanks.



[microsoft.public.dotnet.framework.aspnet]
 
The example shown for ASP would not prevent SQL injection.
You should use ADO parameters in ASP and ADO.NET parameters in ASP.NET where
possible.
A
 
Johnny said:
I read an article about SQL Script Injection, it teaches me how to prevent
it using old fashion ASP:

String: p_strUsername = Replace(Request.Form("txtUsername"), "'", "''")
INT: p_lngID = CLng(Request("ID"))

How about C# in .NET? Any suggestions?

Thanks.
 
Back
Top