将数据从一张表迁移到另一张表的过程当中,经过mysql的concat方法批量生成sql时遇到了一个问题,即进行UPDATE更新操做时若是原表中的字段中包含单引号'或者双引号",那么就会生成不正确的update语句。mysql
缘由固然很简单由于update table set xxx = 'content'
时content通常由英文单引号'或者双引号"包裹起来,使用单引号较多。sql
若是content中包含单引号'时咱们须要对单引号'进行转义或者将content用双引号括起来,这样双引号"里面的单引号'就会被视为普通的字符,同理若是content中包含双引号"那么咱们就能够换成单引号括起来content,这样双引号"就会被视为普通字符。可是若是content中既包含单引号'又包含双引号",这时咱们就不得不对content中的内容进行转义了。函数
学生表student中有如下四条数据,如今要把student表中的四条数据按照id更新到用户表user当中,user表的结构同student同样。加密
有单引号的能够用双引号括起来spa
select concat("update user set name = '",name,"' where id = ",id,";") from student where id = 1;
code
有双引号的能够用单引号括起来对象
select concat("update user set name = \"",name,"\" where id = ",id,";") from student where id = 3;
blog
需使用replace函数将content中的单引号和双引号替换为转义的形式。it
函数介绍:replace(object,search,replace),把object对象中出现的的search所有替换成replace。table
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;
知无不言,言无不尽,百人誉之不加密,百人毁之不加疏。
若是对您有帮助,请不要忘了给翎野君点赞。