mysql单引号双引号(当遇到字段中有单引号或者双引号时出错)

前言

将数据从一张表迁移到另外一张表的过程中,通过mysql的concat方法批量生成sql时遇到了一个问题,即进行UPDATE更新操作时如果原表中的字段中包含单引号'或者双引号",那么就会生成不正确的update语句。

原因当然很简单因为update table set xxx = 'content'时content一般由英文单引号'或者双引号"包裹起来,使用单引号较多。

如果content中包含单引号'时我们需要对单引号'进行转义或者将content用双引号括起来,这样双引号"里面的单引号'就会被视为普通的字符,同理如果content中包含双引号"那么我们就可以换成单引号括起来content,这样双引号"就会被视为普通字符。但是如果content中既包含单引号'又包含双引号",这时我们就不得不对content中的内容进行转义了。

实践

学生表student中有以下四条数据,现在要把student表中的四条数据按照id更新到用户表user当中,user表的结构同student一样。

1、内容中含有单引号

有单引号的可以用双引号括起来

select concat("update user set name = '",name,"' where id = ",id,";") from student where id = 1;

2、内容中含有双引号

有双引号的可以用单引号括起来

select concat("update user set name = \"",name,"\" where id = ",id,";") from student where id = 3;

3、内容中包含双引号和单引号

需使用replace函数将content中的单引号和双引号替换为转义的形式。

函数介绍:replace(object,search,replace),把object对象中出现的的search全部替换成replace。

select concat("update user set name = '",replace(replace(name,"'","\\\'"),"\"","\\\""),"' where id = ",id,";") from student where id = 2;  

对student整表应用以下sql

select concat("update user set name = '",replace(replace(name,"'","\\\'"),"\"","\\\""),"' where id = ",id,";") from student;

得到的结果是:

update user set name = '小明\"' where id = 1;
update user set name = '\'翎\"野' where id = 2;
update user set name = '\'小王' where id = 3;
update user set name = '小李' where id = 4;

我是「翎野君」,感谢各位朋友的:点赞收藏评论,我们下期见。 ​​

,

© 版权声明
THE END
喜欢就支持一下吧
分享