MySQLdb中文输出乱码解决

 1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 '''
4 #=============================================================================
5 # FileName: test.py
6 # Desc:
7 # Author: Tony.Shao
8 # Email: vector.model@gmail.com
9 # HomePage: http://www.xencode.org
10 # Version: 0.0.1
11 # LastChange: 2012-02-21 21:22:00
12 # History:
13 #=============================================================================
14 '''
15 import sys
16 import MySQLdb
17
18 reload(sys)
19 sys.setdefaultencoding('utf-8')
20
21 db = MySQLdb.connect(host='localhost', user='root',
22 passwd='XXXXX', db='resys', charset='utf8')
23 cursor = db.cursor()
24 cursor.execute("SELECT * FROM tb_movies")
25 data_file = file('/home/xcode/Developer/test.txt','w')
26 for row in cursor.fetchall():
27 for data in row:
28 print data
29 data_file.write(str(data))
30 data_file.write(" ")
31 cursor.close()

正常输出

1 快乐的大脚1 2 快乐的大脚2 3 快乐的大脚3 

注意这里row是个tuple(数组)

for row in cursor.fetchall():
for data in row:
print data

直接 print 一个数组,输出的是数组的表示,这里如果不将row循环输出会为

(1L, u'\u5feb\u4e50\u7684\u5927\u811a1') (2L, u'\u5feb\u4e50\u7684\u5927\u811a2') (3L, u'\u5feb\u4e50\u7684\u5927\u811a3') 

 

在华蟒里看到也有人碰到同样的问题

https://groups.google.com/forum/?fromgroups#!topic/python-cn/ZboYmKP3Ni0

转载于:https://www.cnblogs.com/xencode/archive/2012/02/21/2361994.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值