[Mono-list] escaping a string for sql

Aaron Bockover aaron.lists@aaronbock.net
Mon, 07 Mar 2005 14:02:34 -0500


There is probably a better way to do this for normal SQL operations, but
I am using Mono.Data.SqliteClient, and it's much more limited than other
drivers. I wrote a SQL Generator class that builds SQL statements, and
in it, I use this:

using System.Text.RegularExpressions; 

...

public static string EscapeQuotes(string str)
{
	string s = Regex.Replace(str, "'", @"''");
	s = Regex.Replace(s, @"[']+''", @"''");
	return s;
}

This will replace any ' with '' (escaping), but will not replace '' with
''' and so on, so there shouldn't be any need to "Unescape" data later
on.

--Aaron




On Mon, 2005-03-07 at 22:36 +0800, Alan Knowles wrote:
> As far as I can tell, you dont, you use prepared statements and 
> placeholders.
> 
> Regards
> Alan
> 
> James Grant wrote:
> 
> >I know this probably isnt the right place to ask, but I figured someone here 
> >might  know (and google seems useless in this case) -- how do you escape a 
> >string in C# for use in an SQL query?  in php/mysql I would do  
> >mysql_escape_string("string with ' or ` in it")
> >
> >all i'm doing is a simple SQL SELECT based on the input of a text box, but the 
> >text box must handle all input (apostrophe's, quotes, etc) -- here's what 
> >Npgsql is saying when I enter   "apo'strophe" in the textbox.
> >
> >Npgsql.NpgsqlException:
> >syntax error at or near "strophe"
> >Severity: ERROR
> >Code: 42601
> >in <0x00061> Npgsql.NpgsqlConnection:CheckErrors ()
> >
> >Thanks,
> > James
> >
> >  
> >
> 
> _______________________________________________
> Mono-list maillist  -  Mono-list@lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list
> 
>