I am trying to log down sql that execute.
I have a function call LogGenerateReport(String Sql) that will do a insert process to save the data in a database.
The Problem i face is about the SQl ”.
For example:
INSERT INTO TABLE(Sql)
VALUE('SELECT * FROM Sales WHERE SalesID = 'ABC123';')
Its return me error and i know what happened because of the quote.
I try again inside my database where i open a new query and paste above sql and made some modification on it such as.
INSERT INTO TABLE(Sql)
VALUE('SELECT * FROM Sales WHERE SalesID = ''' + 'ABC123' + ''';')
Its return me expected result.
Output:
|Sql |
|SELECT * FROM Sales WHERE SalesID = 'ABC123';|
But back on my .aspx.cs page i have a string builder that store the executed query and before it executed, it need to save the query first.
For example:
System.Text.StringBuilder str = new System.Text.StringBuilder();
str.append("SELECT * FROM Sales WHERE SalesID = 'ABC123';");
api.LogGenerateReport(Convert.tostring(str));
Its return me error as like above because of the quote.
I try to figure it out to overcome this and my idea is
String TempSql = Convert.tostring(str);
TempSql.Replace("'","+'''");
I wont work because of the + symbol is at different position.
Is there any way to overcome this?
To succesfully log any and all SQL queries regardless of their content, you need to apply parameterized commands in the following way:
That way you can avoid escaping anything with NON-STANDARD methods, and protect your code from SQL injection attacks.