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

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