如何在动态SQL命令中添加引号? [英] How to Add Quotes to a Dynamic SQL Command?

查看:309
本文介绍了如何在动态SQL命令中添加引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在数据库中存储和编辑某些字段,该字段涉及一个或多个句子的长字符串。每当我在文本框中输入单引号并将其保存时,都会引发类似
'l'附近的语法不正确的异常。
字符串''之后的引号引起来。 / em>
有什么办法避免这种情况吗?

I am storing and editing some field in a database that involves a long string of one or more sentences. whenever i enter a single quote in the textbox and want to save it it throws an exception like "Incorrect syntax near 'l'. Unclosed quotation mark after the character string ''." is there any idea to avoid that?

编辑:
查询是:

The query is:

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


推荐答案

正如KM所说,不要

执行 this 代替:

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命令中添加引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆