用python訪問sqlite
來源:互聯網
上載者:User
1.首先去www.sqlite.org下載一個sqlite,它是一個嵌入式資料庫,沒有伺服器的概念,windows版的就是一個exe,自己把它放到一個合適的目錄裡,然後把這個目錄加入系統的path變數.
2.然後去找個pysqlite,這是python訪問sqlite的介面,地址在這裡 : http://initd.org/tracker/pysqlite
目前針對不同的python版本,pysqlite有兩個版本:2.3和2.4,請根據自己的python版本選用.
3.然後就可以開啟自己喜歡的編輯器,寫一段測試代碼了.
4.中文處理要注意的是sqlite預設以utf-8編碼儲存.
5.另外要注意sqlite僅支援檔案鎖,換句話說,它對並發的處理並不好,不推薦在網路環境使用,適合單機環境.import pysqlite2.dbapi2 as sqlite
def runTest():
cx = sqlite.connect('test.db')
cu = cx.cursor()
#create
cu.execute('''create table catalog(
id integer primary key,
pid integer,
name varchar(10) unique
)''')
#insert
cu.execute('insert into catalog values(0,0,"張小山")')
cu.execute('insert into catalog values(1,0,"hello")')
cx.commit()
#select
cu.execute('select * from catalog')
print '1:',
print cu.rowcount
rs = cu.fetchmany(1)
print '2:',
print rs
rs = cu.fetchall()
print '3:',
print rs
#delete
cu.execute('delete from catalog where id = 1 ')
cx.commit()
cu.execute('select * from catalog')
rs = cu.fetchall()
print '4:',
print rs
#select count
cu.execute("select count(*) from catalog")
rs = cu.fetchone()
print '5:',
print rs
cu.execute("select * from catalog")
cu.execute('drop table catalog')
if __name__ == '__main__':
runTest()