MySQL导出数据反单引号_使用mysqldump导出数据时对字段中包含的单引号的处理
最近在做一個日志統(tǒng)計項目,有一個輔助表是在MySQL數(shù)據(jù)庫的,現(xiàn)在要將其遷移到Postgresql,自然是先用mysqldump將MySQL里面的數(shù)據(jù)導出,然后再導入到Postgresql即可。但在實際操作過程中,發(fā)現(xiàn)一些字段中本身就含有單引號,在導出的sql語句中,對這樣的單引號使用’\’做了轉(zhuǎn)義處理,比如原來的某個字段的值為:It’s very popular,導出的sql中大概是這樣的格式:’It\’s very popular’,可以看到,字段中的單引號被轉(zhuǎn)義。但使用導出的sql往Postgresql中插入數(shù)據(jù)時,卻報告錯誤,因為Postgresql對’\’作為轉(zhuǎn)義字符并不識別。
Question:
I use mysqldump to backup my mysql database. The problem is that the sql file generated by mysqldump doesn’t escapes single quotes properly.
Here is an example of the mysqldump generated sql script :
INSERT INTO someTable VALUES (1,’This ain\’t escaped correctly’);
That single quote escaping in “ain’t” doesn’t work and it makes the rest of the script being inside that string. Is there a way around this?
Answer:
That output of mysqldump is working as designed, and it is properly escaped, unless you try to restore the dump on a MySQL instance with SQL_MODE=NO_BACKSLASH_ESCAPES set.
There’s an outstanding feature request to make mysqldump use a pair of single-quotes to escape literal single-quotes, as per ANSI SQL. See http://bugs.mysql.com/bug.php?id=65941
In the meantime you might be able to convert from backslash-singlequote to pair-of-singlequotes with a command line this:
mysqldump test | sed -e “s/\\’/”/g” > test-dump.sql
I tried that out briefly by creating a dummy table in my test database and inserting the string “O’Hare” into the table. But that’s hardly a comprehensive test – I take no responsibility for this suggestion working in all cases.
結(jié)合另外一篇博客,完整的導出命令應寫成:
mysqldump -u root -ppassword –no-create-db –no-create-info
–complete-insert –compatible=mssql –default-character-set=utf8 –skip-opt –compact –extended-insert=false dbname tablename|sed “s/\\’/”/g”>tablename.sql
參數(shù)的含義如下:
–no-create-db 不輸出建database的腳本
–no-create-info 不輸出創(chuàng)建table的腳本
–complete-insert 完整的插入,輸出每個字段(如: insert into table(field1,field2,….) values(value1,value2,…))
–compatible=mssql 教本兼容格式,這里是mssql 這樣教本里就會把table的名字和字段名用“號引起來,而不是mssql不能識別的`號。
–default-character-set=utf8 默認編碼
–compact 輸出盡量少的信息
–extended-insert=false 禁用它,可以每行生成一句insert語句,否則只輸出一個。
至此,問題解決。在Postgresql中,兩個單引號表示一個單引號,因此在導出時使用sed命令直接將\’替換成”,就可以將數(shù)據(jù)正確插入到Postgresql中了。
總結(jié)
以上是生活随笔為你收集整理的MySQL导出数据反单引号_使用mysqldump导出数据时对字段中包含的单引号的处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 张靓颖海豚音是哪首歌啊?
- 下一篇: 蒋夜的作者是谁啊?