最开始没注意数据库的编码,使用默认的方式去连接:
- db = web.database(dbn='mysql', user='root', pw='lihuipeng007', host='localhost', db='test')
- sql = '''''''select * from tb_admin_user where login='%s' and password='%s' ''' % (username, password)
- result = db.query(sql)
- print result[0]['name']
这样打印出来就会乱码
后来在数据库连接及打印的时候加上编码转换后就正常:
- db = web.database(dbn='mysql', user='root', pw='lihuipeng007', host='localhost', db='test', charset='latin1')
- sql = '''''select * from tb_admin_user where login='%s' and password='%s' ''' % (username, password)
- result = db.query(sql)
- print result[0]['name'].encode('latin1','ignore')
最后放上服务器测试的时候发现还是会乱码,报的是这个错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)
然后在文件前面加入:
- import sys
- default_encoding = 'utf-8'
- if sys.getdefaultencoding() != default_encoding:
- reload(sys)
- sys.setdefaultencoding(default_encoding)
中文显示终于正常了~~~不容易啊。。