Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add Quotes to a Dynamic SQL Command?

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?

EDIT: The query is:

SqlCommand com = new SqlCommand("UPDATE Questions SET Question = '[" + 
    tbQuestion.Text + "]', Answer = '[" + 
    tbAnswer.Text + "]', LastEdit = '" + 
    CurrentUser.Login + 
    "'WHERE ID = '" + CurrentQuestion.ID + "'");
like image 636
Ahmad Farid Avatar asked Jul 14 '09 11:07

Ahmad Farid


People also ask

How do you put single quotes around variables in a dynamic query?

SET @Query = @Query + ' WHERE ' + '' + @param + ' ' + @operator + ' ' + '' + @val + '' ; Thanks!


1 Answers

As KM said, don't do this!

Do this instead:

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();
        }
    }
}
like image 67
John Saunders Avatar answered Sep 30 '22 08:09

John Saunders