用Python進行SQLite數據庫操作
Python2.5之后,內置了SQLite3,成為了內置模塊,這給我們省了安裝的功夫,只需導入即可~
2. 創建/打開數據庫
在調用connect函數的時候,指定庫名稱,如果指定的數據庫存在就直接打開這個數據庫,如果不存在就新創建一個再打開。
3.數據庫連接對象
打開數據庫時返回的對象cx就是一個數據庫連接對象,它可以有以下操作:
- commit()--事務提交
- rollback()--事務回滾
- close()--關閉一個數據庫連接
- cursor()--創建一個游標
關於commit(),如果isolation_level隔離級別默認,那么每次對數據庫的操作,都需要使用該命令,你也可以設置isolation_level=None,這樣就變為自動提交模式。
4.使用游標查詢數據庫
我們需要使用游標對象SQL語句查詢數據庫,獲得查詢對象。 通過以下方法來定義一個游標。
- execute()--執行sql語句
- executemany--執行多條sql語句
- close()--關閉游標
- fetchone()--從結果中取一條記錄,並將游標指向下一條記錄
- fetchmany()--從結果中取多條記錄
- fetchall()--從結果中取出所有記錄
- scroll()--游標滾動
1. 建表
上面語句創建了一個叫catalog的表,它有一個主鍵id,一個pid,和一個name,name是不可以重復的,以及一個nickname默認為NULL。
2. 插入數據
請注意避免以下寫法:
pid = 200
cu.execute( " ... where pid = '%s' " % pid)
cu.execute( " insert into catalog values (?,?,?,?) " , t)
3.查詢
要提取查詢到的數據,使用游標的fetch函數,如:
[(0, 10 , u ' abc ' , u ' Yu ' ), ( 1 , 20 , u ' cba ' , u ' Xu ' )]
如果我們使用cu.fetchone(),則首先返回列表中的第一項,再次使用,則返回第二項,依次下去.
4.修改
cx.commit()
注意,修改數據以后提交
5.刪除
cx.commit()
6.使用中文
請先確定你的IDE或者系統默認編碼是utf-8,並且在中文前加上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 ' )]
如果要顯示出中文字體,那需要依次打印出每個字符串
....: for element in item:
....: print element,
....:
0 10 魚 Yu
1 20 cba Xu
7.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
-
A 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 [ 31 ]: cu = cx.cursor()
In [ 32 ]: cu.execute( ' select * from catalog ' )
Out[ 32 ]: < sqlite3.Cursor object at 0x05666680 >
In [ 33 ]: r = cu.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
使用列的關鍵詞查詢
Out[ 43 ]: 0
In [ 44 ]: r[ ' name ' ]
Out[ 44 ]: u ' \u9c7c '