python解决mysql乱码问题
来源:互联网 发布:ubuntu 16.04 fcitx 编辑:程序博客网 时间:2024/05/17 00:54
# encoding=utf-8'''Created on 2012-4-6@author: yajunzhang'''import MySQLdb import sysprint sys.getdefaultencoding()conn = MySQLdb.connect(host='*.*.*.*', user='zhang', passwd='8',db='db',charset='utf8') cursor = conn.cursor() count = cursor.execute('select name from category') print '总共有 %s 条记录',count #获取一条记录,每条记录做为一个元组返回 print "只获取一条记录:" result = cursor.fetchone(); print result[0]#print 'ID: %s info: %s' % (result[0],result[1]) print 'info: %s' % result[0]#获取3条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录 print "只获取3条记录:" results = cursor.fetchmany(3) for r in results: print r[0] print "获取所有结果:" #重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative, cursor.scroll(0,mode='absolute') #获取所有结果 results = cursor.fetchall() for r in results: print r[0] conn.close()