一、 安裝
Python 2.5開始提供了對sqlite的支持,帶有sqlite3庫.
沒有sqlite的版本需要去PySqlite主頁上下載安裝包.
二、創建數據庫/打開數據庫
Sqlite使用文件作爲數據庫,你可以指定數據庫文件的位置。
import sqlite3 #導入模塊
cx = sqlite3.connect("d:\\test.db")
#這個是建立在內存裏, 內存中的任何操作都不需要commit
#cx = sqlite3.connect(':memory:')
使 用sqlite的connect可以連接一個數據庫文件,當數據庫文件不存在的時候,它會自動創建。如果已經存在這個文件,則打開這個文件。cx爲數據庫連接對象。
三、操作數據庫的基本對象
3.1 數據庫連接對象
象前面的cx就是一個數據庫的連接對象,它可以有以下操作:
commit()--事務提交
rollback()--事務回滾
close()--關閉一個數據庫連接
cursor()--創建一個遊標
3.2 遊標對象 所有sql語句的執行都要在遊標對象下進行。
cu = cx.cursor()#這樣定義了一個遊標。
遊標對象有以下的操作:
execute()--執行sql語句
executemany--執行多條sql語句
close()--關閉遊標
fetchone()--從結果中取一條記錄
fetchmany()--從結果中取多條記錄
fetchall()--從結果中取出多條記錄
scroll()--遊標滾動
四、使用舉例
4.1 建庫
import sqlite3 #導入模塊
cx = sqlite3.connect("d:\\test.db")
4.2 建表
cu=cx.cursor()
cu.execute("""create table catalog ( id integer primary key, pid integer, name varchar(10) UNIQUE )""")
上面語句創建了一個叫catalog的表,它有一個主鍵id,一個pid,和一個name,name是不可以重複的。
關於sqlite支持的數據類型,在它主頁上面的文檔中有描述,可以參考:Version 2 DataTypes.
4.3 insert(插入)
cu.execute("insert into catalog values(0, 0, 'name1')")
cu.execute("insert into catalog values(1, 0, 'hello')")
cx.commit()
如果你願意,你可以一直使用cu遊標對象。注意,對數據的修改必須要使用事務語句:commit()或rollback(),且對象是數據庫連接對象,這裏爲cx。
4.4 select(選擇)
cu.execute("select * from catalog")
print cu.fetchall()
[(0, 0, 'name1'), (1, 0, 'hello')]
fetchall() 返回結果集中的全部數據,結果爲一個tuple的列表。每個tuple元素是按建表的字段順序排列。注意,遊標是有狀態的,它可以記錄當前已經取到結果的 第幾個記錄了,因此,一般你只可以遍歷結果集一次。在上面的情況下,如果執行fetchone()會返回爲空。這一點在測試時需要注意。
cu.execute("select * from catalog where id = 1")
print cu.fetchone()
(1, 0, 'hello')
對數據庫沒有修改的語句,執行後不需要再執行事務語句。
4.5 update(修改)
cu.execute("update catalog set name='name2' where id = 0")
cx.commit()
cu.execute("select * from catalog")
print cu.fetchone()
(0, 0, 'name2')
4.6
delete(刪除)
cu.execute("delete from catalog where id = 1")
cx.commit()
cu.execute("select * from catalog")
cu.fetchall()
#cu.close()
#cx.close()
[(0, 0, 'name2')]
原文參考:
http://www.cnblogs.com/luckeryin/archive/2009/09/25/1574152.html