有趣生活

当前位置:首页>科技>mysql单引号双引号当遇到字段中有单引号或者双引号时出错

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

发布时间:2026-07-21阅读(1)

导读前言将数据从一张表迁移到另外一张表的过程中,通过mysql的concat方法批量生成sql时遇到了一个问题,即进行UPDATE更新操作时如果原表中的字段中包....前言

将数据从一张表迁移到另外一张表的过程中,通过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;

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

Copyright © 2024 有趣生活 All Rights Reserve吉ICP备19000289号-5 TXT地图HTML地图XML地图