我正在数据库中存储和编辑某些字段,该字段涉及一个或多个句子的长字符串。每当我在文本框中输入单引号并要保存它时,都会引发异常,例如 “’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(); } } }