SQLite3基本使用从shell到python
生活随笔
收集整理的這篇文章主要介紹了
SQLite3基本使用从shell到python
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? ? ? SQLite是一個(gè)輕量級的關(guān)系型數(shù)據(jù)庫,在訪問量不超過10萬PV的中小站點(diǎn)中使用綽綽有余。
并且使用方便,接口簡單,以下從命令行和python接口雙方面介紹SQLite3的基本操作。
? ? ? ? 在linux終端中,通過?sqlite3 a.db 打開a.db數(shù)據(jù)庫,假設(shè)不存在會自己主動創(chuàng)建,創(chuàng)建一個(gè)表格:
create table users(id integer primary key,name text,level integer);然后插入新的數(shù)據(jù): insert into users(name,level) values('李斯',2); insert into users(name,level) values('張三',4); insert into users(name,level) values('王五',3);
顯示表格內(nèi)容: sqlite> .mode column sqlite> .headers on sqlite> select * from users; id name level ---------- ---------- ---------- 1 李斯 2 2 張三 4 3 王五 3
更新李斯的level變?yōu)?。操作例如以下: sqlite> update users set level=1 where name='李斯'; sqlite> select * from users; id name level ---------- ---------- ---------- 1 李斯 1 2 張三 4 3 王五 3
刪除張三的數(shù)據(jù): sqlite> delete from users where name='張三'; sqlite> select * from users; id name level ---------- ---------- ---------- 1 李斯 1 3 王五 3
上面這些操作能夠滿足基本SQLite的使用了。以下通過python的接口調(diào)用:
連接數(shù)據(jù)庫:
>>> import sqlite3 >>> db=sqlite3.connect('a.db') >>> c=db.cursor()插入一個(gè)用戶的信息: >>> c.execute('insert into users(name,level) values("田田蹦",9)') <sqlite3.Cursor object at 0xb711c4a0> >>> db.commit()
所有取出表中的數(shù)據(jù): >>> c.execute('select * from users') <sqlite3.Cursor object at 0xb70e74e0> >>> c.fetchall() [(1, '李斯', 1), (3, '王五', 3), (4, '田田蹦', 9)]
一行一行取出表中數(shù)據(jù): >>> c.execute('select * from users') <sqlite3.Cursor object at 0xb70e7c20> >>> c.fetchone() (1, '李斯', 1) >>> c.fetchone() (3, '王五', 3) >>> c.fetchone() (4, '田田蹦', 9) >>> c.fetchone() == None True
關(guān)閉游標(biāo)對象并關(guān)閉數(shù)據(jù)庫連接: >>> c.close() >>> db.close()
python下對SQLite的更新和刪除操作參考上面的插入操作。是一樣一樣的。很方便。得到的表格數(shù)據(jù)是list,每行數(shù)據(jù)是一個(gè)tuple,興許操作也很方便。
轉(zhuǎn)載請注明:轉(zhuǎn)自http://blog.csdn.net/littlethunder/article/details/24696309
轉(zhuǎn)載于:https://www.cnblogs.com/mengfanrong/p/5251110.html
總結(jié)
以上是生活随笔為你收集整理的SQLite3基本使用从shell到python的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机学院微信公众平台,智慧校园管理,一
- 下一篇: 手机App性能测试工具Genymotio