python学习笔记(十一)使用SQLite

SQLite是一个轻型数据库系统,python内置SQLite3的库,可以直接使用。本文简述SQLite的使用方法,并在文末给出一个未完成的例子。

开始

数据库本质是文件数据,数据库系统的作用是高效管理这些数据文件。一个数据库对应许多表,基本操作主要基于数据库中的这些表。在python中使用SQLite需引入模块:

import sqlite3

建立数据库

con = sqlite3.connect('temp.db')
...
con.commit()
con.close()

这一句连接名为temp的数据库,如果不存在则在目录下建立该数据库,并且返回一个控制句柄,通过这个句柄可以对数据库进行操作。在操作后要通过commit()函数提交。使用完数据库后,要用close()进行关闭。

光标

光标类似控制台下使用SQL的命令行,通过光标可以输入SQL语句或者接收结果。

cursor = con.cursor()
...
cursor.close()

在光标使用完之后要使用close()结束操作。

建立表

表是数据库的基本元素,表中存在着多个键值对,和python中的字典有一定的相似。而且,SQLite中是允许无类型数据的。

cursor.execute('create table user(id,name)')

表的操作

表的操作属于SQL语句的内容,其主要操作有插入:insert、查询:select、删除:delete等。同样是通过execute函数来执行。

cursor.execute('select * from table_name where id = ? and name = ?',('1',14,))
val = cursor.fetchall()
rows = cursor.rowcount

其中fetchall()返回查询的结果,rowcount能统计查询结果的条数。

一个例子

上次爬来的数据是保存在文件下的,在学习数据库的操作后可以将其保存到数据库中。
创建表:

    def create_table(self,table_name = 'servant_data'):
        cursor = self.con.cursor()
        if self.__table_item == '':
            s = ''
            if 1 not in self.__data_dict:
                self.load(1)
            for key in self.__data_dict[1]:
                s = s + key + ','
            self.__table_item = s[:-1]

        try:
            cursor.execute('create table %s(%s)'%(table_name,self.__table_item))
        except:
            pass
        finally:
            pass
        self.__table_name = table_name
        cursor.close()
        self.commit()

将内存中的数据保存到数据库:


    def save_dict_to_db(self,table_name = 'servant_data'):
        self.create_table(table_name)
        cursor = self.con.cursor()
        for i in self.__data_dict:
            cursor.execute('select * from %s where ID = %s'%(table_name,i))
            val = cursor.fetchall()
            if not val:
                s = ''
                for key in self.__data_dict[i]:
                    item = self.__data_dict[i][key]
                    s = s + '\''+ item + '\'' + ','
                s = s[:-1]
                try:
                    cursor.execute('insert into %s(%s)values(%s)'%(table_name,self.__table_item,s))
                except sqlite.OperationalError:
                    print s.encode("GBK", 'ignore')
                finally:
                    pass
        cursor.close()
        self.commit()

按名字查询:

    def search_with_name(self,name_str = 'NAME'):
        name = raw_input('imput name')
        if self.__table_name == '':
            return
        cursor = self.con.cursor()
        cursor.execute('select*from %s where %s glob \'*%s*\''%(self.__table_name,name_str,name))
        print cursor.fetchall() 
        cursor.close()

但由于编码以及数据集的问题,尚不能正确运行。

参考资料:
sqlite下载:http://download.csdn.net/detail/wzh_xwjh/5307149
python下sqlite:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001388320596292f925f46d56ef4c80a1c9d8e47e2d5711000
使用sqlite:http://blog.csdn.net/byxdaz/article/details/5846023

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章