设置mysql中的charset是UTF-8的,然后在python代码文件中设置#coding=utf-8。python从mysql获取数据时,会将数据转成unicode码
# -*- coding: utf-8 -*-
import sys
import MySQLdb
import json
reload(sys)
sys.setdefaultencoding("utf-8")
db="xxx"
user="xxx"
passwd="xxx"
host="xxx"
port=zzz
charset="utf8"
dbconn = MySQLdb.connect(host=host, db=db, port=port, user=user, passwd=passwd, charset=charset, autocommit = True)
cursor = dbconn.cursor()
sql = 'select name,id from t1'
cursor.execute(sql)
rows = cursor.fetchall()
rows[0][0] ### 类型为unicode
str(rows[0][0]) ### 类型为str,若要将中文插入Mysql中,使用这种方式
d = {"1": "我", "2": "们"}
json.dumps(d) ### 字典中的value会转成unicode的形式,插入mysql时,不会显示中文
json.dumps(d,ensure_ascii=False) ### 若要将中文插入Mysql中,使用这种方式