如何向数据库插入带有单引号(')的字符串?
因为插入的字符串被从单引号处截断,造成
SQL语句的语法错误! 解决方法:遍历字符串,把一个(')换成两个(' ')就可以了,在C#里,其实用str.Replace("'", "''");就OK了,这是因为
SQL是用两个单引号来代替一个单引号的,下面举个例子: private void btAdd_Click(object sender, EventArgs e){string chinese = this.txtChinese.Text.Trim(); string english = this.txtEnglish.Text.Trim(); if (chinese == ""){MessageBox.Show("请输入中文!");}else if (english == ""){MessageBox.Show("请输入英文!");}else{oleConnection1.Open(); string
sql = "Select * From info Where chinese='" + CheckString(chinese) + "' And english='" + CheckString(english) + "'"; this.oleCommand1.CommandText = sql; if (null == oleCommand1.ExecuteScalar()){string sql1 = "Insert Into info(chinese,english) Values('" + CheckString(chinese) + "','" + CheckString(english) + "')"; oleCommand1.CommandText = sql1; oleCommand1.ExecuteNonQuery(); MessageBox.Show("信息添加成功!", "提示"); this.txtChinese.Text = ""; this.txtEnglish.Text = "";}else{MessageBox.Show("信息添加失败,中文和英文已经存在了!", "警告");