How to escape simple SQL queries in C# for SqlServer

Posted by sri on Stack Overflow See other posts from Stack Overflow or by sri
Published on 2010-03-08T18:25:16Z Indexed on 2010/03/08 18:36 UTC
Read the original article Hit count: 351

Filed under:
|
|

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 quiet 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.

Thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about sql-server