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
- Change field encoding to utf8mb4:
ALTER TABLE 数据库表名 MODIFY `字段名` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
- Check whether the field code is modified successfully: PS: The field value
SHOW FULL COLUMNS FROM 表名;
is modified successfully .Collation
utf8mb4_unicode_ci
Solution 2: Back up the data and recreate the database table
- backup database data
mysqldump -uroot -p密码 --databases 数据库名 > all_data.sql
- delete database
drop database 数据库名
- recreate the database
create database 数据库名
- 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;
- Import database data
mysql -uroot -p密码 < all_data.sql
- 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! !Collation
utf8mb4_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! ! !