今天在做一个复制功能的时候,发现存在单引号字符串与INSERT INTO 语句的' '产生冲突。
如何向数据库插入带有单引号(')的字符串
private void btAdd_Click(object sender,EventArgs e)
{
string english = this.txtEnglish.Text.Trim();
if (chinese == "")
{
}
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();
this.txtChinese.Text = "";
this.txtEnglish.Text = "";
}
else
oleConnection1.Close();
}
private string CheckString(string str)
string returnStr = "";
if (str.IndexOf("'") != -1) //判断字符串是否含有单引号
returnStr = str.Replace("'","''");
str = returnStr;
return str;