Python初接触:SQLite和Excel操作

来源:互联网 发布:windows官网中文版 编辑:程序博客网 时间:2024/05/30 04:04

昨日,女票拿了一个Excel文档,里面有上万条数据要进行分析,刚开始一个字段分析,Excel用的不错,还能搞定,到后来两个字段的分析,还有区间比如年龄段的数据分析,实在是心疼的不行,于是就想给她程序处理之。

当然,我是一直C++和Qt的,当时就想直接Qt+sqlite3写入数据库,然后就各种数据查询就行了,可做起来却发现,她机器上没有Qt环境,没有C++编译器,得,如果配置环境也得几个小时了,可当时根本没有那么多时间来做,幸好,之前还看过一些Python的东西,并且Python环境好配啊,于是就想用Python实现一个写数据库,查询的功能。于是,行动之。

环境配置

1、下载Python:http://www.python.org/downloads/;
2、下载Excel读取库:http://pypi.python.org/pypi/xlrd;
3、Sqlite3数据库:这个是Python自带的,倒是不用下载了。

编写代码

代码写的很简单,一个类,在构造函数的时候初始化数据库对象,析构的时候释放数据库对象。一个插入数据函数,一个读取Excel函数,话不多说,上代码:

import sqlite3import xlrdclass FileDispose(object):    """docstring for FileDispose"""    def __init__(self, file):        super(FileDispose, self).__init__()        '''初始化数据库实例'''        self.conn = sqlite3.connect(file)        self.cursor = self.conn.cursor()    def __del__(self):        '''释放数据库实例'''        self.cursor.close()        self.conn.close()    '''数据库插入操作'''    def insert(self,id,name,sex,age,score,addr):        sql = 'insert into student(id,name,sex,age,score,addr) values (%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")' % (int(id),name,sex,age,score,addr)        print(sql)        self.cursor.execute(sql)        self.conn.commit()    '''读取Excel文件'''    def readFile(self, file):        data = xlrd.open_workbook(file)        table = data.sheets()[2]        for rowId in range(1, 100):            row = table.row_values(rowId)            if row:                self.insert(rowId,row[0],row[1],row[2],row[3],row[4])fd = FileDispose("F:/test.db")fd.readFile('F:/excel.xlsx')

数据库表是我直接拿SQLiteSpy创建的,字段有id,name,sex,age,score,addr这几个。

0 0
原创粉丝点击