Python 如何操作 SQLite 數(shù)據(jù)庫(kù)
寫(xiě)在之前
SQLite 是一個(gè)小型的關(guān)系型數(shù)據(jù)庫(kù),它最大的特點(diǎn)在于不需要單獨(dú)的服務(wù)、零配置。我們?cè)谥爸v過(guò)的兩個(gè)數(shù)據(jù)庫(kù),不管是 MySQL 還是 MongoDB,都需要我們安裝。安裝之后,然后運(yùn)行起來(lái),其實(shí)這就相當(dāng)于已經(jīng)有一個(gè)相應(yīng)的服務(wù)在跑著。
SQLite 與前面所說(shuō)的兩個(gè)數(shù)據(jù)庫(kù)不同。首先Python 已經(jīng)將相應(yīng)的驅(qū)動(dòng)模塊作為了標(biāo)準(zhǔn)庫(kù)的一部分,只要是你安裝了 Python,就可以使用;再者它可以類似于操作文件那樣來(lái)操作 SQLite 數(shù)據(jù)庫(kù)文件。還有一點(diǎn),SQLite 源代碼不受版權(quán)限制。
建立連接
SQLite 也是一個(gè)關(guān)系型數(shù)據(jù)庫(kù),所以 SQL 可以直接在里面使用。由于 SQLite 的驅(qū)動(dòng)已經(jīng)在 Python 里面了,所以只要引用就可以直接使用,由于我們之前已經(jīng)講過(guò) MySQL 了,所以對(duì)于本次內(nèi)容理解起來(lái)就容易多了。
>>> import sqlite3>>> conn = sqlite3.connect(’lite.db’)
由上面的代碼我們得到了連接對(duì)象,是不是覺(jué)得比 MySQL 連接要簡(jiǎn)單很多呢?在 sqlite3.connect(’lite.db’) 中,如果已經(jīng)有了那個(gè)數(shù)據(jù)庫(kù),就直接連接它,如果沒(méi)有的話,就會(huì)自動(dòng)建一個(gè)。需要注意的是,這里的路徑是可以隨意指定的。
下面的代碼顯示的是連接對(duì)象的屬性和方法:
>>> dir(conn)[’DataError’, ’DatabaseError’, ’Error’, ’IntegrityError’, ’InterfaceError’, ’InternalError’, ’NotSupportedError’, ’OperationalError’, ’ProgrammingError’, ’Warning’, ’__call__’, ’__class__’, ’__delattr__’, ’__dir__’, ’__doc__’, ’__enter__’, ’__eq__’, ’__exit__’, ’__format__’, ’__ge__’, ’__getattribute__’, ’__gt__’, ’__hash__’, ’__init__’, ’__init_subclass__’, ’__le__’, ’__lt__’, ’__ne__’, ’__new__’, ’__reduce__’, ’__reduce_ex__’, ’__repr__’, ’__setattr__’, ’__sizeof__’, ’__str__’, ’__subclasshook__’, ’close’, ’commit’, ’create_aggregate’, ’create_collation’, ’create_function’, ’cursor’, ’execute’, ’executemany’, ’executescript’, ’in_transaction’, ’interrupt’, ’isolation_level’, ’iterdump’, ’rollback’, ’row_factory’, ’set_authorizer’, ’set_progress_handler’, ’set_trace_callback’, ’text_factory’, ’total_changes’]
建立游標(biāo)
這一步其實(shí)跟 MySQL 也很類似,連接了數(shù)據(jù)庫(kù)之后,要建立游標(biāo)對(duì)象:
>>> cur = conn.cursor()
接下來(lái)就是對(duì)數(shù)據(jù)庫(kù)內(nèi)容的操作,都是用游標(biāo)對(duì)象方法來(lái)實(shí)現(xiàn):
>>> dir(cur)[’__class__’, ’__delattr__’, ’__dir__’, ’__doc__’, ’__eq__’, ’__format__’, ’__ge__’, ’__getattribute__’, ’__gt__’, ’__hash__’, ’__init__’, ’__init_subclass__’, ’__iter__’, ’__le__’, ’__lt__’, ’__ne__’, ’__new__’, ’__next__’, ’__reduce__’, ’__reduce_ex__’, ’__repr__’, ’__setattr__’, ’__sizeof__’, ’__str__’, ’__subclasshook__’, ’arraysize’, ’close’, ’connection’, ’description’, ’execute’, ’executemany’, ’executescript’, ’fetchall’, ’fetchmany’, ’fetchone’, ’lastrowid’, ’row_factory’, ’rowcount’, ’setinputsizes’, ’setoutputsize’]
我們?cè)诶锩婵吹搅艘幌盗形覀兪煜さ拿Q:close()、execute()、fetchall() 等。
1.創(chuàng)建數(shù)據(jù)庫(kù)表
面對(duì) SQLite 數(shù)據(jù)庫(kù),我們之前熟悉的 SQL 指令都可以用:
>>> create_table = 'create table books (title,author,language)'>>> cur.execute(create_table)<sqlite3.Cursor object at 0x104f296c0>
這樣就在數(shù)據(jù)庫(kù) lite.db 中建立了一個(gè)表 books。對(duì)這個(gè)表可以增加數(shù)據(jù):
>>> cur.execute(’insert into books values('python basic','rocky','python')’)<sqlite3.Cursor object at 0x104f296c0>
為了保證數(shù)據(jù)能夠保存,還要進(jìn)行如下操作:
>>> conn.commit()>>> cur.close()>>> conn.close()
以上,在剛才建立的數(shù)據(jù)庫(kù)中已經(jīng)有了一個(gè)表 books,表中已經(jīng)有了一條記錄。
2.查詢
保存以后我們來(lái)查詢一下:
>>> conn = sqlite3.connect(’lite.db’)>>> cur = conn.cursor()>>> cur.execute(’select * from books’)<sqlite3.Cursor object at 0x104f297a0>>>> cur.fetchall()[(’python basic’, ’rocky’, ’python’)]
3.批量插入
我們來(lái)給 books 表中多增加一些內(nèi)容,以便于我們進(jìn)行其它的操作:
>>> books = [('first book','first','c'),('second book','second','c++'),('third book','third','java')]
這次我們來(lái)一個(gè)批量插入:
>>> cur.executemany(’insert into books values (?,?,?)’,books)<sqlite3.Cursor object at 0x104f297a0>>>> conn.commit()
接下來(lái)我們用循環(huán)語(yǔ)句來(lái)打印一下查詢結(jié)果:
>>> rows = cur.execute(’select * from books’)>>> for row in rows:... print(row)... (’python basic’, ’rocky’, ’python’)(’first book’, ’first’, ’c’)(’second book’, ’second’, ’c++’)(’third book’, ’third’, ’java’)
4.更新
正如我們前面所說(shuō)的,在 cur.execute() 中,可以寫(xiě) SQL 語(yǔ)句來(lái)操作數(shù)據(jù)庫(kù):
>>> cur.execute('update books set title=’physics’ where author=’first’')<sqlite3.Cursor object at 0x104f297a0>>>> conn.commit()
接下來(lái)我們按照條件查詢來(lái)看一看:
>>> cur.execute('select * from books where author=’first’')<sqlite3.Cursor object at 0x104f297a0>>>> cur.fetchall()[(’physics’, ’first’, ’c’)]
5.刪除
刪除也是操作數(shù)據(jù)庫(kù)必須的動(dòng)作:
>>> cur.execute('select * from books')<sqlite3.Cursor object at 0x104f297a0>>>> cur.fetchall()[(’python basic’, ’rocky’, ’python’), (’physics’, ’first’, ’c’), (’third book’, ’third’, ’java’)]
最后不要忘記在完成對(duì)數(shù)據(jù)庫(kù)的操作以后,一定記得給人家「關(guān)上門(mén)」:
>>> cur.close()>>> conn.close()
寫(xiě)在之后
基本的知識(shí)差不多就是這些,當(dāng)然肯定不局限于此。在實(shí)際的編程中我們肯定會(huì)遇到很多的問(wèn)題,大家記得要多多去查閱官方文檔,學(xué)會(huì)解決問(wèn)題。
至此,Python 操作數(shù)據(jù)這一部分就結(jié)束了,其實(shí)不光是這一個(gè)章節(jié)的結(jié)束,我計(jì)劃里面的整個(gè)「零基礎(chǔ)入門(mén)學(xué)習(xí) Python」這個(gè)系列也到此結(jié)束了,后續(xù)隨著我碰到的知識(shí)的增加,還會(huì)再給大家更新關(guān)于 Python 方面的東西,讓我們一起加油。
如果你覺(jué)得本篇文章對(duì)你有所幫助的話,歡迎點(diǎn)贊 + 關(guān)注,期待和你的交流。
The end。
以上就是Python 如何操作 SQLite 數(shù)據(jù)庫(kù)的詳細(xì)內(nèi)容,更多關(guān)于python操作 SQLite 數(shù)據(jù)庫(kù)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP新手必備的基礎(chǔ)知識(shí)2. asp文件用什么軟件編輯3. Docker 啟動(dòng)Redis 并設(shè)置密碼的操作4. CentOS郵箱服務(wù)器搭建系列——SMTP服務(wù)器的構(gòu)建( Postfix )5. PHP基礎(chǔ)之生成器4——比較生成器和迭代器對(duì)象6. JS中6個(gè)對(duì)象數(shù)組去重的方法7. vue+element開(kāi)發(fā)一個(gè)谷歌插件的全過(guò)程8. Vue axios獲取token臨時(shí)令牌封裝案例9. 通過(guò)IEAD+Maven快速搭建SSM項(xiàng)目的過(guò)程(Spring + Spring MVC + Mybatis)10. 利用CSS制作3D動(dòng)畫(huà)

網(wǎng)公網(wǎng)安備