mysql string sanitisation
What would be the best/fastest way to sanitize strings?
Right now I wrote this function, but I don't know how efficient this really is, nor if I'm even covering all my bases:
Code:
public static string Sanitize(string instr)
{
string ret=instr;
ret=ret.Replace("\\","\\\\");
ret=ret.Replace("\"","\\\"");
ret=ret.Replace("`","\\`");
ret=ret.Replace("\'","\\'");
return ret;
}
Is there a better way to do this?
Re: mysql string sanitisation
What are you trying to achieve?
Re: mysql string sanitisation
I am not sure what do you mean by sanitisation? However if you are talking about running queries from C# code then you should look at parametrized queries. Then you would not need to handle any special characters at all.
Re: mysql string sanitisation
Basically I want to ensure that stuff like quotes gets properly escaped. And I noticed an error in my function so I just corrected it now.
I'm just wondering if there are other control characters or special sequences I should be worried about filtering out.
Re: mysql string sanitisation
As i said in my earlier post, you should not be worried about escaping the special characters. If you do it in a right way and use Parametrized Queries then you will never have to worry about the special characters. Just take a look at how SQLCommand, ODBCCommand or OleDBCommand samples work on msdn.
Re: mysql string sanitisation
Red, it's still not clear why you need to do this.
Generally you need to escape when writing string literals into your code, but otherwise you just pass the data through.
For example, consider receiving the following string from the db:
Certainly you wouldn't want to escape that; otherwise it would end up as:
Quote:
What\'s happening?
That being said, can you provide a specific example of the string coming from the database and how you would like it to appear (i.e. before and after)?