Skip to content

Instantly share code, notes, and snippets.

@jtr109
Last active December 3, 2018 05:50
Show Gist options
  • Save jtr109/adeebf70527f30bad2c1a279344ffcb4 to your computer and use it in GitHub Desktop.
Save jtr109/adeebf70527f30bad2c1a279344ffcb4 to your computer and use it in GitHub Desktop.
创建数据表以适应 utf8mb4

Python3 PyMySQL Raise Incorrect String Value When Inserting UTF-8 Data

Description

Python3 + PyMySQL 的环境, 如果在数据库中写入中文, 会出现报错:

pymysql.err.InternalError: (1366, "Incorrect string value: '\\xE6\\xB5\\x8B\\xE8\\xAF\\x95' for column 'description' at row 1")

查询发现主要原因是 mysql 对 utf8 的支持是最大 3 个 bytes, 而写入是以 4 byptes 为准的.

所以需要在创建的时候指定 charset 为 utf8mb4, 创建方法见 snippet

Reference:

CREATE DATABASE utf_test
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment