我正在在数据库中存储和编辑一些字段,其中涉及一个或多个句子的长字符串。每当我在文本框中输入单个报价并要保存它时,它会引发一个异常“'l'的语法不正确。字符串之后的未封闭引号''。有什么想法避免这种情况吗?

编辑:查询是:

SqlCommand com = new SqlCommand("UPDATE Questions SET Question = '[" + 
    tbQuestion.Text + "]', Answer = '[" + 
    tbAnswer.Text + "]', LastEdit = '" + 
    CurrentUser.Login + 
    "'WHERE ID = '" + CurrentQuestion.ID + "'");
有帮助吗?

解决方案

正如KM所说, 不要这样做!

这个 反而:

private static void UpdateQuestionByID(
    int questionID, string question, string answer, string lastEdited)
{
    using (var conn = new SqlConnection(connectionString))
    {
        conn.Open();
        const string QUERY =
            @"UPDATE Questions " +
            @"SET Question = @Question, Answer = @Answer, LastEdit = @LastEdited " +
            @"WHERE ID = @QuestionID";
        using (var cmd = new SqlCommand(QUERY, conn))
        {
            cmd.Parameters.AddWithValue("@Question", question);
            cmd.Parameters.AddWithValue("@Answer", answer);
            cmd.Parameters.AddWithValue("@LastEdited", lastEdited);
            cmd.Parameters.AddWithValue("@QuestionID", questionID);
            cmd.ExecuteNonQuery();
        }
    }
}

其他提示

如果要将单个报价包含在SQL字段中,请使用单个报价将其逃脱

'''Test''' = 'Text'

这是针对SQL Server的。

编写一个存储的功能来进行您的字段编辑并使用SQL参数来保存值。行情没关系。如果您不希望存储的Proc至少使用参数标记构建SQL文本,并使用SQL参数。

很难给您一个特定的答案,因为您不列出所使用的数据库或应用程序语言。

您必须动态地构建SQL,并且刺痛中的报价被解释为字符串的末端。根据所使用的数据库,您需要逃脱打算在SQL命令中使用的每个字符串中的单个引号。在尝试运行查询之前,可以通过打印查询来查看。

您没有提及您正在调用数据库的应用程序,但是当您构建命令时,您需要使用fix_quotes()命令或使用语言提供的命令:

SqlCommand com = new SqlCommand("UPDATE Questions SET Question = '[" + FIX_QUOTES(tbQuestion.Text) + "]', Answer = '[" + FIX_QUOTES(tbAnswer.Text) + "]', LastEdit = '" + FIX_QUOTES(CurrentUser.Login) + "'WHERE ID = '" + FIX_QUOTES(CurrentQuestion.ID) + "'"); – A

对于这种类型的动态查询非常容易 SQL注射攻击. 我建议使用存储过程或参数列表调用数据库。

在MSSQL中,您可以将报价加倍:

my dodg'y test          -> 'my dodg''y test'
my 'quoted' string      -> 'my ''quoted string'''
'first and last quotes' -> '''first and last quotes'''

正如某些人已经说过的那样,添加额外的报价将解决问题。我可以确认Oracle也是如此(其他答案对MSSQL和SQL Server有效)。我认为使用存储过程对此是过分的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top