加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

[SqlServer]如何向数据库插入带有单引号(')的字符串

发布时间:2020-12-12 16:05:20 所属栏目:MsSql教程 来源:网络整理
导读:今天在做一个复制功能的时候,发现存在单引号字符串与INSERT INTO 语句的' '产生冲突。 在网络上找到了一个这样功能 如何向数据库插入带有单引号(')的字符串 用SQL语句往数据库某字段(字符型)中插入字符串,但是当该字符串中带有单引号(')时就会出错!

今天在做一个复制功能的时候,发现存在单引号字符串与INSERT INTO 语句的' '产生冲突。

在网络上找到了一个这样功能

如何向数据库插入带有单引号(')的字符串 用SQL语句往数据库某字段(字符型)中插入字符串,但是当该字符串中带有单引号(')时就会出错!因为插入的字符串被从单引号处截断,造成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("信息添加失败,中文和英文已经存在了!","警告"); ? ? ? ? ? ? ? ? oleConnection1.Close(); ? ? ? ? } ? ? ? ? private string CheckString(string str) ? ? ? ? ? ? string returnStr = ""; ? ? ? ? ? ? if (str.IndexOf("'") != -1) //判断字符串是否含有单引号 ? ? ? ? ? ? ? ? returnStr = str.Replace("'","''"); ? ? ? ? ? ? ? ? str = returnStr; ? ? ? ? ? ? return str; 这里为什么要用另一个变量(returnStr)来接收替换后的值呢?不然替换会失效,调用Replace()方法不能改变str本身,string对象虽然是引用类型,但它具有很多值类型特征,比较特殊。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读