用Python進行SQLite數據庫操作


 

簡單的介紹

      SQLite數據庫是一款非常小巧的嵌入式開源數據庫軟件,也就是說沒有獨立的維護進程,所有的維護都來自於程序本身。它是遵守ACID的關聯式數據庫管理系統,它的設計目標是嵌入式的,而且目前已經在很多嵌入式產品中使用了它,它占用資源非常的低,在嵌入式設備中,可能只需要幾百K的內存就夠了。它能夠支持Windows/Linux/Unix等等主流的操作系統,同時能夠跟很多程序語言相結合,比如 Tcl、C#、PHP、Java等,還有ODBC接口,同樣比起Mysql、PostgreSQL這兩款開源世界著名的數據庫管理系統來講,它的處理速度比他們都快。SQLite第一個Alpha版本誕生於2000年5月. 至今已經有10個年頭,SQLite也迎來了一個版本 SQLite 3已經發布。

 

安裝與使用

 

 

1.導入 Python SQLITE數據庫模塊

     Python2.5之后,內置了SQLite3,成為了內置模塊,這給我們省了安裝的功夫,只需導入即可~

import sqlite3

 

2. 創建/打開數據庫 

     在調用connect函數的時候,指定庫名稱,如果指定的數據庫存在就直接打開這個數據庫,如果不存在就新創建一個再打開。

cx = sqlite3.connect("E:/test.db")
     也可以創建數據庫在內存中。
con = sqlite3.connect(":memory:")

 

3.數據庫連接對象

    打開數據庫時返回的對象cx就是一個數據庫連接對象,它可以有以下操作:

  1. commit()--事務提交   
  2. rollback()--事務回滾   
  3. close()--關閉一個數據庫連接   
  4. cursor()--創建一個游標

    關於commit(),如果isolation_level隔離級別默認,那么每次對數據庫的操作,都需要使用該命令,你也可以設置isolation_level=None,這樣就變為自動提交模式。

 

4.使用游標查詢數據庫 

    我們需要使用游標對象SQL語句查詢數據庫,獲得查詢對象。 通過以下方法來定義一個游標。

cu=cx.cursor()

 

     游標對象有以下的操作:
  1. execute()--執行sql語句   
  2. executemany--執行多條sql語句   
  3. close()--關閉游標   
  4. fetchone()--從結果中取一條記錄,並將游標指向下一條記錄   
  5. fetchmany()--從結果中取多條記錄   
  6. fetchall()--從結果中取出所有記錄   
  7. scroll()--游標滾動  

1. 建表

cu.execute("create table catalog (id integer primary key,pid integer,name varchar(10) UNIQUE,nickname text NULL)")

 

上面語句創建了一個叫catalog的表,它有一個主鍵id,一個pid,和一個name,name是不可以重復的,以及一個nickname默認為NULL。

 

2. 插入數據 

請注意避免以下寫法:

# Never do this -- insecure 會導致注入攻擊

pid=200
c.execute("... where pid = '%s'" % pid)
正確的做法如下,如果t只是單個數值,也要采用t=(n,)的形式,因為元組是不可變的。 
for t in[(0,10,'abc','Yu'),(1,20,'cba','Xu')]:
    cx.execute("insert into catalog values (?,?,?,?)", t)
簡單的插入兩行數據,不過需要提醒的是,只有提交了之后,才能生效.我們使用數據庫連接對象cx來進行提交commit和回滾rollback操作.
cx.commit()

 

 

3.查詢

cu.execute("select * from catalog") 

要提取查詢到的數據,使用游標的fetch函數,如:

In [10]: cu.fetchall()
Out[10]: [(0, 10, u'abc', u'Yu'), (1, 20, u'cba', u'Xu')]

如果我們使用cu.fetchone(),則首先返回列表中的第一項,再次使用,則返回第二項,依次下去.

 

4.修改

In [12]: cu.execute("update catalog set name='Boy' where id = 0")
In [13]: cx.commit()

注意,修改數據以后提交

 

5.刪除

cu.execute("delete from catalog where id = 1")  
cx.commit() 

 

6.使用中文

請先確定你的IDE或者系統默認編碼是utf-8,並且在中文前加上u 

x=u'魚'
cu.execute("update catalog set name=? where id = 0",x)
cu.execute("select * from catalog")
cu.fetchall()
[(0, 10, u'\u9c7c', u'Yu'), (1, 20, u'cba', u'Xu')]

如果要顯示出中文字體,那需要依次打印出每個字符串

 
In [26]: for item in cu.fetchall():
   ....:     for element in item:
   ....:         print element,
   ....:     print
   ....: 
0 10 魚 Yu
1 20 cba Xu
 

 

7.Row類型

 

Row提供了基於索引和基於名字大小寫敏感的方式來訪問列而幾乎沒有內存開銷。 原文如下:

 

sqlite3.Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.

 

Row對象的詳細介紹

class  sqlite3. Row

Row instance serves as a highly optimized row_factory for Connection objects. It tries to mimic a tuple in most of its features.

It supports mapping access by column name and index, iteration, representation, equality testing and len().

If two Row objects have exactly the same columns and their members are equal, they compare equal.

Changed in version 2.6: Added iteration and equality (hashability).

keys ( )

This method returns a tuple of column names. Immediately after a query, it is the first member of each tuple in Cursor.description.

New in version 2.6.

    下面舉例說明

 
In [30]: cx.row_factory = sqlite3.Row

In [31]: c = cx.cursor()

In [32]: c.execute('select * from catalog')
Out[32]: <sqlite3.Cursor object at 0x05666680>

In [33]: r = c.fetchone()

In [34]: type(r)
Out[34]: <type 'sqlite3.Row'>

In [35]: r
Out[35]: <sqlite3.Row object at 0x05348980>

In [36]: print r
(0, 10, u'\u9c7c', u'Yu')

In [37]: len(r)
Out[37]: 4

In [39]: r[2]            #使用索引查詢
Out[39]: u'\u9c7c'

In [41]: r.keys()
Out[41]: ['id', 'pid', 'name', 'nickname']

In [42]: for e in r:
   ....:     print e,
   ....: 
0 10 魚 Yu
 

 使用列的關鍵詞查詢

In [43]: r['id']
Out[43]: 0

In [44]: r['name']
Out[44]: u'\u9c7c'


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM