Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape simple SQL queries in C# for SqlServer

Tags:

c#

sql

sql-server

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.

like image 265
sc45 Avatar asked Mar 08 '10 18:03

sc45


People also ask

How do I escape a SQL statement?

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.

What characters should be escaped in SQL?

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 (\_).


1 Answers

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.

like image 155
Seva Alekseyev Avatar answered Oct 18 '22 01:10

Seva Alekseyev