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

posted on 2012-02-21 21:43  Tony.Shao  阅读(382)  评论(0编辑  收藏  举报

导航