MySQL Error:Warning: (1366, "Incorrect string value: '\\xF0\\x9F\\x98\\x82\\xF0\\x9F...' for column 'xxx' at row 2")

时间:2023-03-09 08:16:41
MySQL Error:Warning: (1366, "Incorrect string value: '\\xF0\\x9F\\x98\\x82\\xF0\\x9F...' for column 'xxx' at row 2")

bug现象

使用连接数据库的可视化软件插入 emoj 表情数据、生僻字,可以正常插入。(导致我一直以为跟表情没有任何关系,谷歌出来一堆跟修改数据库、表、字段 的编码的结果....)但是一启动程序插入新数据就会报这个错误,一一检查过数据库、表、字段的编码都是正确的,后面只能把插入数据的代码撸下来单独跑,在代码里面尝试插入 生僻字、emoj 表情,终于重现了bug。。。 然后谷歌的关键词转向了 python。

peewee 解决方法

  

# 1、创建连接
cache_database = PooledMySQLDatabase(
"database",
**{
"host": "xxx",
"port": 3306,
"user": "xxx",
"password": "xxx"
}
) # 2、获取游标
cursor = cache_database.cursor()
# 3、划重点:修改数据库连接是以utf8mb4编码格式进行的连接
cursor.execute('SET NAMES utf8mb4;') # 4、定义模型类
class BaseModel(Model):
class Meta:
database = cache_database class TestModel(BaseModel):
id = BigIntegerField(primary_key=True, sequence=True)
code = FixedCharField(max_length=32, default='')
。。。 class Meta:
db_table = 'test_table' # 5、插入数据
def retry_store_cache(db, table, cache_info_list):
n = 1
while True:
try:
if db.is_closed():
db.connect()
if not table.table_exists():
table.create_table()
with db.atomic():
table.insert_many(cache_info_list).execute()
except Exception as e:
print("<error>: {}".format(e.with_traceback(sys.exc_info()[2])))
print("retry store data {}s later".format(n))
time.sleep(n)
n *= 2
if n > 8:
raise Exception(e)
else:
break data_info = [
{
'ratio': 1.0,
'city': 340,
'poi': 4075062903,
'code': '5193fb98f2307202858f8ec6644f58e5',
'create_time': 1574714741,
'data': '