Kaushik DB
Kaushik DB

Reputation: 93

What are the characters that I need to escape in a SQL query

What are the characters that I need to check for and escape when inserting a string?

INSERT INTO gamedata (gamename, url, dlink) 
VALUES ('mady's run', 'http://www.sdfa.com', 'http://extabit.com/sdf')</code>

How do I escape these characters?
I'm using C# and managing database with SQL Server Management Studio 2008.

Upvotes: 3

Views: 1330

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499900

Don't escape them. Just don't include the values in your SQL at all. Instead, use parameterized SQL and supply the values directly for the parameters. No escaping, no quoting, no conversions - and no risk of SQL injection attacks.

See the documentation for SqlCommand.Parameters for an example.

You should apply this to all values - not just ones which you anticipate having "special" characters. It separates the code (SQL) from the data (the values), avoids SQL injection attacks, and also avoids unnecessary conversions (which can really cause problems for date/time values and numbers, if you're not careful).

Upvotes: 22

Related Questions