• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

How do you sanitize a string for SQL

Noobsa44

Member
I've just started lookin at using SQL for my windows application and I've started to consider how I should sanitize my string input. I would appreciate seeing both a quick and dirty way and the more secure, and probably more complex way (even if it's an API call).

The reason I want to see both methods is because I'm less worried that some one will try to wreck the DB on purpose (inner facing corp. app), but more worried that someone will do it accidentally. With this in mind, I care about performance slightly more than ensuring no attack could be successful, but if the quick/dirty method is just as fast as the more secure method, then I'll stick with security.
 
Essentially: 1) validate your user input at the interface; 2) use parameterized queries and never dump any user string directly into a query string; 3) handle db exceptions gracefully.

Do those things and it is highly unlikely anyone can get a bad query to your db.
 
I've started using SQL parameters, however I wonder if they catch all cases. For example, do I still need to worry about a string like "This string won't be alright" where the single quote is not gracefully taken care of or can I remove my single quote fixing function? Thanks for all the helpful suggestions.

BTW KB, SQL Server 2005 Compact Edition does not support Stored Procedures, so I was not able to implement your suggestion.

For future reference, does anyone know if LINQ (VS 2008/.net 3.5) protects the database from SQL injections and/or invalid strings?
 
Originally posted by: KB
The best way to sanitize strings is to use Stored Procedures.

Guy here at work is obsessed with stored procedures. He's happy with them due to the fact they kinda make things easier, and they're reusable.
 
Originally posted by: Tarrant64
Originally posted by: KB
The best way to sanitize strings is to use Stored Procedures.

Guy here at work is obsessed with stored procedures. He's happy with them due to the fact they kinda make things easier, and they're reusable.

I think a lot of them myself, but you have to keep it clear what should go in them. I think stored procs are applicable for logic needed to transactionally stitch together data from the database for application use. The app shouldn't need to own code that is specific to the database structure and implementation. Stored procs should not, imo, be used for business logic.
 
Back
Top