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

本文关键字:保存 HTML 内容 数据库 | 更新日期: 2023-09-27 18:11:16

我的页面上有一个文本区域。在该区域,我必须添加一些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>'

我使用asp mvc和剃刀引擎。我不知道,也许我需要转换成html。我还为ArticleText属性添加了这个:

[AllowHtml]        
        public string ArticleText { get; set; }

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

string sql = @"insert into tbl_articles 
                               (Text) values 
                               ("'" + article.ArticleText"'"+")";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.ExecuteNonQuery();

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

哇,不,不,不。您的代码容易受到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();
}

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

尝试这样保存:

string sqlQuery = "INSERT INTO tbl_articles (Text) VALUES (@text)";
SqlCommand cmd = new SqlCommand(sqlQuery, db.Connection);
cmd.Parameters.Add("@text", article.ArticleText);
cmd.ExecuteNonQuery();

尝试:

string sql = @"insert into tbl_articles 
                               (Text) values 
                               (@articleText)";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@articleText",
                Server.HtmlEncode(article.articleText));
                cmd.ExecuteNonQuery();

这是一个典型的Sql注入攻击的例子。

您需要转义'字符,因为如果Html包含'字符,它将在执行SQL语句时中断。

编辑:用Darins的解决方案来解决问题

这应该被参数化:

    public void foo(string connectionString, string textToSave)
    {
        var cmdString = "insert into tbl_articles (text) values (@text)";
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            using (SqlCommand comm = new SqlCommand(cmdString, conn))
            {
                comm.Parameters.Add("@text", SqlDbType.VarChar, -1).Value = textToSave;
                comm.ExecuteNonQuery();
            }
        }
    }

(这是一般的想法,它不像写的那样完全起作用)