Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string into safe SQL String?

I'm generating some sql insert statements from a bunch of text files.

These text files are generally user input data. I would like to sanitize this data so that it's not going to break the insert statement.

For example, some of the input data, people have used the word Don't. The "'" in don't will lead the sql statement to think the string has ended and therefore cause an error.

Is there any .NET method I can call to kind of convert all of these characters to either escape codes or safe characters?

like image 561
Diskdrive Avatar asked Apr 03 '11 10:04

Diskdrive


People also ask

How do I modify a string in SQL?

If you'd like to replace a substring with another string, simply use the REPLACE function. This function takes three arguments: The string to change (which in our case was a column). The substring to replace.

Can you parse a string in SQL?

In parsing strings, it's essential to know the information within the string, the positions of each piece of information, and their sizes or lengths. One of the parsing functions is SQL SUBSTRING. It only needs the string to parse, the position to start extraction, and the length of the string to extract.

How do you escape special characters in SQL Server?

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.


1 Answers

There is only a single character you have to escape: ansi 0x27, aka the single quote:

safeString = unsafeString.Replace("'","''"); 
like image 198
Andomar Avatar answered Oct 06 '22 08:10

Andomar