I have no idea even where to start on this problem. I’m trying to do something very simple, create a string with quotation marks in it. I have no problem (even in C#) with this, but this one particular chunk of code is behaving very oddly (at least by my know-how).
Match timeExtractor = (new Regex(@"'(?<time>\d{4}:\d{2}:\d{2} \d{1,2}:\d{2}:\d{2})'")).Match(SQLstatement);
string time = timeExtractor.Groups["time"].ToString();
Match visitIDExtractor = (new Regex(@"VALUES\('(?<visit_id>[\d]+)'")).Match(SQLstatement);
string visit_id = visitIDExtractor.Groups["visit_id"].ToString();
string s = "Select * From MeasurementsData Where Time =\"" + time + "\" AND Visit_ID =\"" + visit_id + "\";";
queryCommand.CommandText = s;
My problem is my resulting string looks something along the lines of:
“Select * From MeasurementsData Where Time = \”2009:11:11 11:11:11\” AND Visit_ID….”
With the backslashes appearing in the expression. The following test code run in another application produces the results I desire (the ones without the backslashes)
string time = @"2009:11:11 11:11:11";
string visit_id = @"1279";
string s = "Select * From MeasurementsData Where Time =\"" + time + "\" AND Visit_ID =\"" + visit_id + "\";";
Console.WriteLine(s);
These desired results are produced with or without the preceding @ symbol. I fiddled with it for a while.
Adding an extra backslash escapes the backslash and not the quotes (as I believe it should) and doesn’t escape the quotes so it doesn’t compile.
Removing the backslash treats caused the quote not to be escaped and once again it will not compile (as I expected).
But this is what really gets me. I try just removing the backslashes with the following addition to the code:
Match timeExtractor = (new Regex(@"'(?<time>\d{4}:\d{2}:\d{2} \d{1,2}:\d{2}:\d{2})'")).Match(SQLstatement);
string time = timeExtractor.Groups["time"].ToString();
Match visitIDExtractor = (new Regex(@"VALUES\('(?<visit_id>[\d]+)'")).Match(SQLstatement);
string visit_id = visitIDExtractor.Groups["visit_id"].ToString();
string s = "Select * From MeasurementsData Where Time =\"" + time + "\" AND Visit_ID =\"" + visit_id + "\";";
s = s.Replace("\\", "");
queryCommand.CommandText = s;
And it doesn’t do anything to the string! It still contains the backslashes. I need someone with more experience than myself to show me what I’m doing wrong or how to get around this behavior.
Thanks for the help once again.
You should go with:
This way you don’t need to put those quotes and it’s safe against SQL injection attacks.