python 编码问题

Jave.Lin Jave.Lin 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
源代码:

#coding="utf-8"

import sys
import MySQLdb
import types
import codecs

conn = MySQLdb.connect(host='...', user='...', passwd='...', db='...', port=8001, charset='gbk')
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)

n = cursor.execute("select * from t_award_info limit 2");
fAllData = cursor.fetchall();
print "fAllData:\n" + str(fAllData);

for row in fAllData:
for r in row:
k = r.encode("gbk")
print k
print k + " = " + (str(row[k]).encode("gbk") if (row[k] is types.StringType) else str(row[k]).encode("gbk"))

cursor.close();
conn.close();


运行后报错:
Traceback (most recent call last):
File "F:\WorkFiles\Study\python\test_mysql\TestMySql.py", line 21, in <module>
print k + " = " + (str(row[k]).encode("gbk") if (row[k] is types.StringType) else str(row[k]).encode("gbk"))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

就这行报错:
print k + " = " + (str(row[k]).encode("gbk") if (row[k] is types.StringType) else str(row[k]).encode("gbk"))
...全文

相关推荐

评论 31
收藏 已收藏
分享
返回顶部
Jave.Lin
脚本语言 37,738 成员 34,208 内容