將數據從一張表遷移到另一張表的過程當中,經過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;
知無不言,言無不盡,百人譽之不加密,百人毀之不加疏。
若是對您有幫助,請不要忘了給翎野君點贊。