Is there some reason not to write safe database code? I don't think so.
Everyone should get into the habit of executing SQL safely, so you won't even have to think about it when you write public apps.
Also consider that a lot of code that's intended to be private will end up becoming accessible publicly months or years later. For example, "hey this intranet app for inventory reporting is useful, why don't we upload it to our public website for our business partners to use?"
- Use parameters to separate unvalidated data from the SQL query.
- You can interpolate validated data into SQL queries. That is, if you have code to test that a variable can only be an integer (for example), then it's safe to treat it as an integer.
- For other dynamic parts of a query (table names, column names, expressions, etc.) you can't use query parameters. But you can map user input to hardcoded strings. E.g. if user enters
1
, then sort by date
column. If user enters 2
then sort by status
column.
- Ignore programmers who say "just use stored procedures!" as though that has anything to do with defense against SQL injection. It doesn't.