SQLite3基本使用從shell到python

來源:互聯網
上載者:User

        SQLite是一個輕量級的關係型資料庫,在訪問量不超過10萬PV的中小網站中使用綽綽有餘。而且使用方便,介面簡單,下面從命令列和python介面兩方面介紹SQLite3的基本操作。

        在linux終端中,通過 sqlite3 a.db 開啟a.db資料庫,如果不存在會自動建立,建立一個表格:

create table users(id integer primary key,name text,level integer);

然後插入新的資料:

insert into users(name,level) values('李斯',2);insert into users(name,level) values('張三',4);insert into users(name,level) values('王五',3);

顯示表格內容:

sqlite> .mode columnsqlite> .headers onsqlite> select * from users;id          name        level     ----------  ----------  ----------1           李斯      2         2           張三      4         3           王五      3 

更新李斯的level變為1,操作如下:

sqlite> update users set level=1 where name='李斯';sqlite> select * from users;id          name        level     ----------  ----------  ----------1           李斯      1         2           張三      4         3           王五      3      

刪除張三的資料:

sqlite> delete from users where name='張三';sqlite> select * from users;id          name        level     ----------  ----------  ----------1           李斯      1         3           王五      3     

上面這些操作可以滿足基本SQLite的使用了,下面通過python的介面調用:

串連資料庫:

>>> import sqlite3>>> db=sqlite3.connect('a.db')>>> c=db.cursor()

插入一個使用者的資訊:

>>> c.execute('insert into users(name,level) values("田田蹦",9)')<sqlite3.Cursor object at 0xb711c4a0>>>> db.commit()

全部取出表中的資料:

>>> c.execute('select * from users')<sqlite3.Cursor object at 0xb70e74e0>>>> c.fetchall()[(1, '李斯', 1), (3, '王五', 3), (4, '田田蹦', 9)]

一行一行取出表中資料:

>>> c.execute('select * from users')<sqlite3.Cursor object at 0xb70e7c20>>>> c.fetchone()(1, '李斯', 1)>>> c.fetchone()(3, '王五', 3)>>> c.fetchone()(4, '田田蹦', 9)>>> c.fetchone() == NoneTrue

關閉遊標對象並關閉資料庫連接:

>>> c.close()>>> db.close()

python下對SQLite的更新和刪除操作參考上面的插入操作,是一樣一樣的,非常方便,得到的表格資料是list,每行資料是一個tuple,後續操作也非常方便。


轉載請註明:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.