用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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.