首先找到这里的解决方法,
count = cursor.fetchall()
for i in count:
idc_a = i[0]
if isinstance(idc_a, unicode):
idc_a = idc_a.encode('utf-8')
print idc_a
但只能解决查询显示乱码问题
后来继续查资料,找到了这里,
解决方法很简单拿,和数据库建立连接后,执行:
db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')
"db" is the result of MySQLdb.connect, and "dbc" is the result of db.cursor().
这样基本解决了。在查看评论时,还看到了一种解决方法:
就是在连接数据库时,指定连接字符集
A lot of useless methods, mate. It is enough to connect with charset="utf8" param.
db = MySQLdb.connect(host="localhost", user = "root", passwd = "", db = "testdb", use_unicode=True, charset="utf8")
当然以上解决方案前提是,数据库在设计时为utf8,表的字符集也要创建为utf8:
修改表字符集:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name; 关于修改MySQL默认字符集,参见这边文章:————>