Converting MySQL table with incorrectly encoded data to UTF-8

后端 未结 1 1253
孤城傲影
孤城傲影 2020-12-14 12:44

I\'ve got a big ol\' MySQL 5.1 database, and for a variety of stupid reasons, I\'ve been storing, I believe, UTF8 characters encoded as LATIN1 in a UTF8 table. It\'s... stra

相关标签:
1条回答
  • 2020-12-14 13:06

    This method below looks really promising & better yet, beautiful in its simplicity. The idea is you mysqldump your entire database as latin1, & then import it re-encoded as utf-8.

    Export:

    mysqldump -u [user] -p --opt --quote-names --skip-set-charset --default-character-set=latin1 [database] > dump.sql

    Import:

    mysql -u [user] -p --default-character-set=utf8 [database] < dump.sql

    I take no credit for this solution, it's completely from Gareth Price's blog. It has worked for everyone who has left him a comment so far: "Wow man you just saved my life. I did not spent 2 hours on this, but 2 days" caught my attention.

    Update #1: Looks like Gareth wasn't the first to discover this.

    Update #2: I just tried this & it worked beautifully for my UTF8-stored-as-latin1 database. Just make sure you switch the default charset on your database to utf8 before importing, or else you'll end up with plain question marks where the special characters were. Of course this might have plenty of other ramifications so test like hell first.

    ALTER SCHEMA [database] DEFAULT CHARACTER SET utf8;

    And if you have any tables that aren't set to the schema default:

    ALTER TABLE [table] CHARACTER SET = DEFAULT;

    (same idea if you have any column-specific charset settings, you'll have to do a ALTER TABLE [table] CHANGE COLUMN [settings] without specifying CHARACTER SET so it goes back to the table default)

    0 讨论(0)
提交回复
热议问题