How to fix aggresive characters in SQL queries?

T

Tomas Machala

Hi,

I'm looking for some way how to make strings with aggresive characters safe
for usement in SQL queries for Microsoft SQL - just something, what would
add slashes before such characters.
Is there any function for that?

Thanks.
 
B

blackstaronline.net

You can use;

str1 = str1.Replace("'", "\'")

You can also change quotes to the HTML code for a quote like this;

str1 = str1.Replace("'", "'")

When it gets sent to the screen it will appear as a '

Its hard to see but its taking single quote and replacing it with
\single quote. I use this all the time. I also have lots of data that
gets entered for web viewing only so I use the .Replace to change
VBCRLF's to <BR> so that the text appears exactly how it was entered in
the text box. Like this;

str1 = str.Replace(vbCrlf, "<br>")

Hope this helps,
Jeremy Reid
http://hgtit.com
 
K

Karl Seguin [MVP]

No.

That's why ADO.NET has parameterized queries..so you don't have to worry
abou tit. using string replacements will eventually land you in trouble
'cuz someone's gonna figure out a unicode character string or something
that'll eventually circumvent it. Plus it's messy.

command.CommandText = "SELECT blah from Table where X = @x");
command.Parameters.Add("@X", SqlDbType.VarChar, 64).value = someVariable;

no need to do anything more...

Another advantage to this is it makes your code easily upgradable to
sprocs...or downgradable to inline queries.

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top