How do I change a MySQL table to UTF-8?

前端 未结 5 520
野趣味
野趣味 2020-12-15 03:57

I know there are many settings for a language for a table and a database.

I already created the database. I believe when I created it, it was default/LATIN. I want

5条回答
  •  生来不讨喜
    2020-12-15 04:35

    1) Database default character set and collation:

    SELECT @@character_set_database, @@collation_database;
    

    Altered via: ALTER DATABASE CHARACTER SET utf8 COLLATE utf8_general_ci;

    2) Table default character set and collation:

    SELECT T.table_name, CCSA.character_set_name 
    FROM information_schema.TABLES T, information_schema.COLLATION_CHARACTER_SET_APPLICABILITY CCSA 
    WHERE CCSA.collation_name = T.table_collation AND T.table_schema = "YOUR_DB";`
    

    Altered via: ALTER TABLE [table_name] CHARACTER SET utf8 COLLATE utf8_general_ci

    3) Column character set and collation:

    SELECT c.TABLE_NAME, c.COLUMN_NAME, c.CHARACTER_SET_NAME, c.COLLATION_NAME 
    FROM information_schema.COLUMNS c
    WHERE c.table_schema = "YOUR_DB";`
    

    Altered via: ALTER TABLE [table_name] CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci

    The third one requires that you disable foreign key checks for the data conversion. So putting this all together:

    DELIMITER //
    CREATE PROCEDURE migrate_charset_to_utf8()
      BEGIN
        DECLARE done TINYINT DEFAULT 0;
        DECLARE curr_table VARCHAR(64);
    
        DECLARE table_cursor CURSOR FOR
        SELECT T.table_name
          FROM information_schema.TABLES T
          WHERE T.TABLE_TYPE = 'BASE TABLE' AND
            T.TABLE_SCHEMA = 'YOUR_DB';
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    
        OPEN table_cursor;
    
        table_loop: LOOP
          FETCH table_cursor INTO curr_table;
          IF done THEN
            LEAVE table_loop;
          END IF;
    
          # Convert table data(columns) charset
          SET @sql_str1 = CONCAT("ALTER TABLE ", curr_table, " CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
          PREPARE stmt1 FROM @sql_str1;
          EXECUTE stmt1;
          DEALLOCATE PREPARE stmt1;
    
          # Set table's default charset e.g for new columns added
          SET @sql_str2 = CONCAT("ALTER TABLE ", curr_table, " CHARACTER SET utf8 COLLATE utf8_general_ci");
          PREPARE stmt2 FROM @sql_str2;
          EXECUTE stmt2;
          DEALLOCATE PREPARE stmt2;
    
        END LOOP table_loop;
    
        CLOSE table_cursor;
      END//
    
    DELIMITER ;
    
    
    SET @@FOREIGN_KEY_CHECKS = 0;
    CALL migrate_charset_to_utf8();
    SET @@FOREIGN_KEY_CHECKS = 1;
    
    ALTER DATABASE CHARACTER SET utf8 COLLATE utf8_general_ci;
    

    EDIT: look here instead

提交回复
热议问题