我知道当你想在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"}
有什么解决办法吗?
1条答案
按热度按时间sd2nnvve1#
你需要设置
ensure_ascii=False
打电话的时候json.dumps()
.例如,