python读取mysql中数据保存至列表

来源:互联网 发布:linux 重启命令卡住 编辑:程序博客网 时间:2024/05/19 16:38

# -*- coding:utf-8 -*-
import MySQLdb#库名:python;表名:studentsconn = MySQLdb.connect(host='localhost',user='root',passwd='',db='python',charset='utf8')cursor = conn.cursor()    count = cursor.execute('select mail from students')    mail_list=[]#获取所有结果     results = cursor.fetchall()result=list(results)    for r in result:        #print 'mail:%s ' % r       mail_list.append(('<span style="color:#ff0000;">%s' % r</span>))print mail_list#游标归零,默认mode='relative'cursor.scroll(0,mode='absolute') count = cursor.execute('select name from students') name_list=[]results=cursor.fetchall()result=list(results)for r in result:    #print '%s' % r    #print type('%s' % r)    name_list.append(('%s' % r))#for i in range(6):#    print name_list[i]conn.close()   

以上是代码。

有一些注意点:

首先,python读取mysql数据需要调用MySQLdb模块。

results=cursor.fetchall()result=list(results)
这个地方由于fetchall方法返回的一个元组,而在后续操作(另一段代码)中,需要的是列表形式的数据,所以将其转换为list类型。

for r in result:        #print 'mail:%s ' % r       mail_list.append((<span style="background-color: rgb(255, 0, 0);">'%s' % r</span>))print mail_list
红色代码部分是用来格式化 r 的,因为如果不这样的,列表中的项是这样的'u'xxxx@xxxx.com'',说实话,我也没想到其他什么好方法,自己在字符串处理和编码的格式这一块的基础好弱!!暂时先这样吧…回去好好巩固基础…>_<


最后,如果列表中有中文的话,使用循环输出就可以了,在后续操作中直接使用下标运算符即可。

0 0