python 读取mysql数据,生成svg图片python
pygalmysql
MySQLdb:sql
安装:pip install mysql-python数据库
下载:这里下载编程
# coding=utf-8 import pygal import MySQLdb def get_data(): db=MySQLdb.connect(host='localhost',user='root',passwd='***',db='movie',charset='utf8') cursor = db.cursor() cursor.execute('select grade,count(2) from movie_info group by grade;') datas=cursor.fetchall() count=[] for data in datas: count.append(int(data[1])) #grade=data[0] #count=data[1] return count def main(): a=range(81,97) grade = [] for b in range(81,97): c=b/10.0 grade.append(c) chart_count=get_data() #for chart_count in chart_data: movie_chart=pygal.Line() movie_chart.title='movie chart' movie_chart.x_labels=map(str, grade) movie_chart.add('count',chart_count) movie_chart.render_to_file(r'C:\Users\legolas\Desktop\movie_chart.svg') if __name__ == '__main__': main()
操做数据库segmentfault
在我上一篇文章中生成过爬虫数据库,大家能够先看下,在这里,先用
MySQLdb
模块的connect
方法建立连接对象,接着建立一个cursor光标对象.数组
注意:连接/光标模式是数据库编程中经常使用的模式
app
连接模式除了要连接数据库以外,还要发送数据库信息,处理回滚操做,建立新的光标对象,等等。svg
一个光标跟踪一种状态信息,好比跟踪数据库的使用状态,当有多个数据库,正好须要向全部数据库写内容,就须要多个光标来处理,光标内包含最后一次的查询结果,因此能够使用 fetchone() 方法获取一条数据,
一个链接能够用多个光标。
工具
处理数据库数据
经过
datas=cursor.fetchall()
获取到tuple格式的数据,先定义一个空的list
用来装数据。用for
遍历读出数据。select grade,count(2) from movie_info group by grade;
查询评分,并统计各个评分的数量,按评分高低排序。
主程序
分析豆瓣电影top250,能够看出,分数在8.1至9.7之间,为了方便,直接经过→
for b in range(81,97): c=b/10.0
生成
`8.1,8.2,8.3,8.4......9.7
数组movie_chart=pygal.Line()
生成折线图....诶,扯不下去了,结贴睡觉。