I use an API that expects a SQL string. I take a user input, escape it and pass it along to the API. The user input is quite simple. It asks for column values. Like so:
string name = userInput.Value;
Then I construct a SQL query:
string sql = string.Format("SELECT * FROM SOME_TABLE WHERE Name = '{0}'", name.replace("'", "''"));
Is this safe enough? If it isn't, is there a simple library function that make column values safe:
string sql = string.Format("SELECT * FROM SOME_TABLE WHERE Name = '{0}'", SqlSafeColumnValue(name));
The API uses SQLServer as the database.
Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.
The escape character (\) needs to be escaped as (\\). The single quote (') needs to be escaped as (\') or ('') in single-quote quoted strings. The double quote (") needs to be escaped as (\") or ("") in double-quote quoted strings. The wild card character for a single character (_) needs to be escaped as (\_).
Since using SqlParameter is not an option, just replace ' with '' (that's two single quotes, not one double quote) in the string literals. That's it.
To would-be downvoters: re-read the first line of the question. "Use parameters" was my gut reaction also.
EDIT: yes, I know about SQL injection attacks. If you think this quoting is vulnerable to those, please provide a working counterexample. I think it's not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With