python - 在Python中将从字典转储的字符串(其中包含utf8字符)插入到mysql

标签 python mysql character-encoding

我知道当你想向mysql插入一些utf8字符时,你只需像这样编码你的字符:

# ... set the db to utf8-friendly
# ... some connection initialization

stmt = """INSERT INTO test (id, name) VALUES (%s, %s)"""
cursor.execute(stmt, (1001, u"小明".encode("utf8"))
conn.commit()

# ... close connection

但是如果我有一本包含 utf8 字符的字典,并且我将脚本编写如下:

mydict = {u"名字": u"小明", "sex": "male"}
mydict_str = json.dumps(mydict)

stmt = """INSERT INTO test (id, params) VALUES (%s, %s)"""
cursor.execute(stmt, (1001, mydict_str))
conn.commit()    

然后我得到了这个:

---- + -----------
 ID  |    params
---- + -----------
1001 | {"\u540d\u5b57": "\u5c0f\u660e", "sex": "male"} # what I want here is {"名字": "小明"...}

我尝试了这个,但什么也没发生,插入了相同的记录:

mydict = {u"名字".encode("utf8"): u"小明".encode("utf8"), "sex": "male"}

有什么解决办法吗?

最佳答案

调用json.dumps()时需要设置ensure_ascii=False

例如,

mydict_str = json.dumps(mydict, ensure_ascii=False)

关于python - 在Python中将从字典转储的字符串(其中包含utf8字符)插入到mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50280199/

相关文章:

c# - Web 服务需要 Python 列表作为参数。需要从C#调用

mysql - Case 语句总是给出 1. MySQL

python - Django:不同数据库中的 save() 方法

python - model = Django 元类中的 User

php - 如何在 mysql WHERE 查询中使用 SUBSTRING()

Python 提取 mysql 到 csv

java - 如何将 UTF8 转换为 Unicode

java - mysql 5.0无法存储utf8

java - crontab 更改 jar 执行时的字符编码

python - 是否可以忽略一行的 pyright 检查?