菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
82
0

mysql 进行update时,要更新的字段中有单引号或者双引号导致不能批量生成sql的问题

原创
05/13 14:22
阅读数 1839

前言

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

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

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

实践

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

image.png

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;

后记

知无不言,言无不尽,百人誉之不加密,百人毁之不加疏。

如果对您有帮助,请不要忘了给翎野君点赞。

发表评论

0/200
82 点赞
0 评论
收藏