Python sqlite模塊
sqlite是非常著名的開源嵌入式數(shù)據(jù)庫軟件,它可以嵌入到其他程序中使用,并且提供SQL接口用來查詢,非常方便。它的官方站點為http://www.sqlite.org。
windows版本的python2.5已經(jīng)自帶了sqlite3這個模塊,是可以直接使用的。
python的數(shù)據(jù)庫模塊有統(tǒng)一的接口標(biāo)準(zhǔn),所以數(shù)據(jù)庫操作都有統(tǒng)一的模式,基本上都是下面幾步(假設(shè)數(shù)據(jù)庫模塊名為db):
1. 用db.connect創(chuàng)建數(shù)據(jù)庫連接,假設(shè)連接對象為conn
2. 如果該數(shù)據(jù)庫操作不需要返回結(jié)果,就直接用conn.execute查詢,根據(jù)數(shù)據(jù)庫事務(wù)隔離級別的不同,可能修改數(shù)據(jù)庫需要conn.commit
3. 如果需要返回查詢結(jié)果則用conn.cursor創(chuàng)建游標(biāo)對象cur, 通過cur.execute查詢數(shù)據(jù)庫,用cur.fetchall/cur.fetchone/cur.fetchmany返回查詢結(jié)果。根據(jù)數(shù)據(jù)庫事 務(wù)隔離級別的不同,可能修改數(shù)據(jù)庫需要conn.commit
4. 關(guān)閉cur, conn
[代碼] [Python]代碼
04 | conn = sqlite3.connect( "D:\aaa.db" ) |
05 | conn.isolation_level = None |
07 | conn.execute( "create table if not exists t1(id integer primary key autoincrement, name varchar(128), info varchar(128))" ) |
09 | conn.execute( "insert into t1(name,info) values ('zhaowei', 'only a test')" ) |
15 | cur.execute( "select * from t1" ) |
18 | print 'row:' , cur.rowcount |
20 | print 'desc' , cur.description |
28 | cur.execute( "select * from t1" ) |
31 | print 'row:' , cur.rowcount |
37 | print 'row:' , cur.rowcount |
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。