如何在数据库中保存HTML内容

111*_*110 4 c# sql-server asp.net asp.net-mvc razor

我的页面上有文字区域.在那个区域,我必须添加一些HTML代码并将其保存到数据库中.它适用于简单的html,但是当我从"维基百科"中选择一些文本并粘贴它并尝试在需要执行SQL查询时保存我遇到以下错误的异常:

Incorrect syntax near 's'.
The identifier that starts with '. Interestingly, old maps show the name as&nbsp;<em>Krakow</em>.</p>
<p>Kragujevac experienced a lot of historical turbulence, ' is too long. Maximum length is 128.
The identifier that starts with '>Paleolithic</a>&nbsp;era. Kragujevac was first mentioned in the medieval period as related to the public square built in a sett' is too long. Maximum length is 128.
The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.
The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.
Unclosed quotation mark after the character string '>Belgrade Pashaluk</a>.</p>'
Run Code Online (Sandbox Code Playgroud)

我正在使用asp mvc和razor引擎.我不知道也许我需要以某种方式填写HTML.我还为ArticleText属性添加了这个:

[AllowHtml]        
        public string ArticleText { get; set; }
Run Code Online (Sandbox Code Playgroud)

这是保存到数据库的代码:

string sql = @"insert into tbl_articles 
                               (Text) values 
                               ("'" + article.ArticleText"'"+")";

                SqlCommand cmd = new SqlCommand(sql, conn);

                cmd.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 31

哇,不,不,不.您的代码容易受到SQL注入攻击,如果您不使用参数化查询,则会发生非常糟糕的事情.所以使用参数化查询.

using (var conn = new SqlConnection("some conn string"))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "insert into tbl_articles (Text) values (@Text)";
    cmd.Parameters.AddWithValue("@Text", article.ArticleText);
    cmd.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)

每次+在构建SQL查询时使用运算符连接字符串时,您都会做一些非常危险和错误的事情.