Inserting an HTML document into a database (SQL problem)
-
Hello, I have the following code:
strCmd = "UPDATE [TBl] SET [text] = " + htmldoc + " where id = 11"; OleDbCommand cmd2 = new OleDbCommand(strCmd, conn); cmd2.ExecuteNonQuery();
Where "htmldoc" is a variable that contains the content of a big html file with lot of quotes extra... so when I execute the code I'm getting an error. How can I fix that? Thanks in advance. -
Hello, I have the following code:
strCmd = "UPDATE [TBl] SET [text] = " + htmldoc + " where id = 11"; OleDbCommand cmd2 = new OleDbCommand(strCmd, conn); cmd2.ExecuteNonQuery();
Where "htmldoc" is a variable that contains the content of a big html file with lot of quotes extra... so when I execute the code I'm getting an error. How can I fix that? Thanks in advance.That is not the problem. Quotation marks has no special meaning at all in a string in SQL. The problem is that you forgot the apostrophes around the string. There are other characters that you should encode, though, as they may appear in the html code. You should encode apostrophes, and if you are using an MySQL database you should also encode backslashes.
--- b { font-weight: normal; }
-
Hello, I have the following code:
strCmd = "UPDATE [TBl] SET [text] = " + htmldoc + " where id = 11"; OleDbCommand cmd2 = new OleDbCommand(strCmd, conn); cmd2.ExecuteNonQuery();
Where "htmldoc" is a variable that contains the content of a big html file with lot of quotes extra... so when I execute the code I'm getting an error. How can I fix that? Thanks in advance.Hi Your problem is, quite possibly, the fact you're using concatenated command text. If the HTML document contains any apostrophe characters, the command will fail. Even worse, if the HTML document contained specially crafted SQL commands, your whole database could be wiped out or an attacker could read your entire database freely. This security risk and bug in your code is known as SQL injection. Here's how to fix the problem and remove the security risk:
strCmd = "UPDATE [TBl] SET [text] = @HtmlInput where id = 11";
OleDbCommand cmd2 = new OleDbCommand(strCmd, conn);
OleDbParameter htmlParameter = new OleDbParameter("@HtmlInput", htmlDoc);
cmd2.Parameters.Add(htmlParameter);
cmd2.ExecuteNonQuery();Note that this assumes htmlDoc variable to be of type string. p.s. next time use <pre> tags to surround your code snippets.
Tech, life, family, faith: Give me a visit. I'm currently blogging about: God-as-Judge, God-as-Forgiver The apostle Paul, modernly speaking: Epistles of Paul Judah Himango