How to convert latin1_swedish_ci data into utf8_general_ci?

前端 未结 2 750
渐次进展
渐次进展 2020-12-08 11:39

I have a MySQL database with all the table fields collation as

latin1_swedish_ci

It has almost 1000 of the records already stored and now

相关标签:
2条回答
  • 2020-12-08 11:59

    one funny thing.

    CONVERT TO CHARSET and CONVERT()/CAST() suggested by Anshu will work fine if charset in the table is in right encoding.

    If for some reason latin1 column containts utf8 text, CONVERT() and CAST() will not be able to help. I had "messed" my database with that setup so spend bit more time on solving this.

    to fix this in addition to character set conversion, there are several exercises required.

    1. "Hard one" is to recreate the database from dump that will be converted via console
    2. "Simple one" is to convert row by row or table by table:
    INSERT INTO UTF8_TABLE (UTF8_FIELD)
    SELECT convert(cast(convert(LATIN1_FIELD using latin1) as binary) using utf8)
      FROM LATIN1_TABLE;

    basically, both cases will process string to original symbols and then to right encoding, that won't happen with simple convert(field using encoding) from table; command.

    0 讨论(0)
  • 2020-12-08 12:07

    Export your table. Drop the table. Open the export file in the editor. Edit it manually where the table structure is created.

    old query:

    CREATE TABLE `message` (
      `message_id` int(11) NOT NULL,
      `message_thread_id` int(11) NOT NULL,
      `message_from` int(11) NOT NULL,
      `message_to` int(11) NOT NULL,
      `message_text` longtext NOT NULL,
      `message_time` varchar(50) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    new query: ( suppose you want to change message_text field. )

    CREATE TABLE `message` (
      `message_id` int(11) NOT NULL,
      `message_thread_id` int(11) NOT NULL,
      `message_from` int(11) NOT NULL,
      `message_to` int(11) NOT NULL,
      `message_text` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
      `message_time` varchar(50) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    save the file and import back to the database.

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