Dealing with the problem of storing emoji symbols in MYSQL and reporting errors

Mysql encountered pymysql.err.OperationalError: (1267, "Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '='")an error inserting data.

Found an emoji in the content ! !

In my database connection, pymysql.connect is set charset='utf8mb4', and when creating a database table CHARSET=utf8, the storage type of the corresponding field for this view is utf8_general_ci, emoji symbols cannot be stored in utf8 encoding format, and need to be changed to utf8mb4.

Solution 1: Modify the field codes that need to save special symbols separately

  1. Change field encoding to utf8mb4:
    ALTER TABLE 数据库表名 MODIFY `字段名` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    
  2. Check whether the field code is modified successfully: PS: The field value SHOW FULL COLUMNS FROM 表名;
    is modified successfully .Collationutf8mb4_unicode_ci

Solution 2: Back up the data and recreate the database table

  1. backup database datamysqldump -uroot -p密码 --databases 数据库名 > all_data.sql
  2. delete databasedrop database 数据库名
  3. recreate the databasecreate database 数据库名
  4. Create a new database table and change the encoding to utf8mb4 CHARSET=utf8mb4:
    CREATE TABLE IF NOT EXISTS `数据库表名`(
               `id` INT UNSIGNED AUTO_INCREMENT,
               `字段1` VARCHAR(100) NOT NULL,
               `字段2` INT NOT NULL,
               PRIMARY KEY ( `id` )
            )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    
  5. Import database datamysql -uroot -p密码 < all_data.sql
  6. Then re-insert the content with emojis and it works fine! ! PS: At this time, it is normal to check the field value
    in the database table and save the emoji! !Collationutf8mb4_0900_ai_ci

What is the difference between several character encodings?

Several character encodings mentioned above: utf8_general_ci utf8mb4_0900_ai_ci utf8mb4_unicode_ci
study it again when you have time! ! !

Guess you like

Origin blog.csdn.net/wzx77/article/details/123380144