Python?操作SQLite3數(shù)據(jù)庫(kù)的實(shí)現(xiàn)示例
從 Python3.x 版本開(kāi)始,在標(biāo)準(zhǔn)庫(kù)中已經(jīng)內(nèi)置了 SQLite3 模塊,它可以支持 SQLite3 數(shù)據(jù)庫(kù)的訪問(wèn)和相關(guān)的數(shù)據(jù)庫(kù)操作。在需要操作 SQLite3 數(shù)據(jù)庫(kù)數(shù)據(jù)時(shí),只須在程序中導(dǎo)入 SQLite3 模塊即可。Python 語(yǔ)言操作 SQLite3 數(shù)據(jù)庫(kù)的基本流程如下所示。
(1) 導(dǎo)入相關(guān)庫(kù)或模塊(SQLite3)。
(2) 使用 connect() 連接數(shù)據(jù)庫(kù)并獲取數(shù)據(jù)庫(kù)連接對(duì)象。它提供了以下方法:
- .cursor() 方法來(lái)創(chuàng)建一個(gè)游標(biāo)對(duì)象
- .commit() 方法來(lái)處理事務(wù)提交
- .rollback() 方法來(lái)處理事務(wù)回滾
- .close() 方法來(lái)關(guān)閉一個(gè)數(shù)據(jù)庫(kù)連接
(3) 使用 con.cursor() 獲取游標(biāo)對(duì)象。
(4) 使用游標(biāo)對(duì)象的方法(execute()、executemany()、fetchall()等)來(lái)操作數(shù)據(jù)庫(kù),實(shí)現(xiàn)插入、修改和刪除操作,并查詢獲取顯示相關(guān)的記錄。在 Python 程序中,連接函數(shù) sqlite3.connect() 有如下兩個(gè)常用參數(shù)。
- database: 表示要訪問(wèn)的數(shù)據(jù)庫(kù)名。
- timeout: 表示訪問(wèn)數(shù)據(jù)的超時(shí)設(shè)定。
(5) 使用 close() 關(guān)閉游標(biāo)對(duì)象和數(shù)據(jù)庫(kù)連接。數(shù)據(jù)庫(kù)操作完成之后,必須及時(shí)調(diào)用其 close() 方法關(guān)閉數(shù)據(jù)庫(kù)連接,這樣做的目的是減輕數(shù)據(jù)庫(kù)服務(wù)器的壓力。
使用 SQLite3 創(chuàng)建表
使用 sqlite3 模塊的 connect 方法來(lái)創(chuàng)建/打開(kāi)數(shù)據(jù)庫(kù),需要指定數(shù)據(jù)庫(kù)路徑,不存在則創(chuàng)建一個(gè)新的數(shù)據(jù)庫(kù)。
con=sqlite3.connect('/home/blctrl/sqlite-db/first.db')下面實(shí)例代碼演示使用 SQLite3 創(chuàng)建數(shù)據(jù)庫(kù)的過(guò)程。
# 導(dǎo)入 sqlite3 模塊
import sqlite3
# 1.硬盤上創(chuàng)建連接
con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
# 獲取 cursor 對(duì)象
cur = con.cursor()
# 執(zhí)行 sql 創(chuàng)建表
sql = '''
CREATE TABLE t_person(
pno INTEGER PRIMARY KEY AUTOINCREMENT ,
pname varchar(30) NOT NULL,
age INTEGER)
'''
try:
cur.execute(sql)
except Exception as e:
print(e)
print('創(chuàng)建表失敗')
finally:
# 關(guān)閉游標(biāo)
cur.close()
# 關(guān)閉連接
con.close()在IPython下測(cè)試:
In [1]: import sqlite3
In [2]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
In [3]: cur = con.cursor()
In [4]: sql = '''
...: CREATE TABLE t_person(
...: pno INTEGER PRIMARY KEY AUTOINCREMENT ,
...: pname varchar(30) NOT NULL,
...: age INTEGER)
...: '''
...:
In [5]: try:
...: cur.execute(sql)
...: print('create Table successfully!')
...: except Exception as e:
...: print(e)
...: print("Failed to create table!")
...: finally:
...: cur.close()
...: con.close()
...:
create Table successfully!使用 SQLite3 插入數(shù)據(jù)
調(diào)用游標(biāo)對(duì)象的 execute 執(zhí)行插入的 sql,使用 executemany() 執(zhí)行多條 sql 語(yǔ)句,使用 executemany()比循環(huán)使用execute()執(zhí)行多條sql語(yǔ)句效率高.
示例: 使用SQLite3插入一條數(shù)據(jù)
# 導(dǎo)入 sqllite3 模塊
import sqlite3
# 硬盤上創(chuàng)建連接
con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
# 獲取 cursor 對(duì)象
cur = con.cursor()
# 構(gòu)造sql插入語(yǔ)句
sql = 'insert into t_person(pname,age) values(?,?)'
try:
cur.execute(sql,('XRR',23))
# 插入多條
cur.executemany(sql, [('XFS', 25),('XPS', 21), ('XRD', 30)])
# 提交事務(wù)
con.commit()
print('插入成功')
except Exception as e:
print(e)
print('插入失敗')
con.rollback()
finally:
# 關(guān)閉游標(biāo)
cur.close()
# 關(guān)閉連接
con.close()
在IPython中進(jìn)行單條數(shù)據(jù)插入的測(cè)試:
In [12]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
In [13]: cur = con.cursor()
In [14]: sql = 'insert into t_person(pname,age) values(?,?)'
In [15]: try:
...: cur.execute(sql, ('XRR',28))
...: con.commit()
...: print("Insert successfully")
...: except Exception as e:
...: print(e)
...: print("Insert failed")
...: con.rollback()
...: finally:
...: cur.close()
...: con.close()
...:
Insert successfully在IPython中進(jìn)行多條數(shù)據(jù)插入的測(cè)試:
In [16]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
In [17]: cur = con.cursor()
In [18]: sql = 'insert into t_person(pname,age) values(?,?)'
In [19]: try:
...: cur.executemany(sql, [('XFS', 25),('XPS', 21), ('XRD', 30)])
...: con.commit()
...: print("Many insert successfully")
...: except Exception as e:
...: print(e)
...: print("Many insert failed")
...: con.rollback()
...: finally:
...: cur.close()
...: con.close()
...:
Many insert successfully使用 SQLite3 查詢數(shù)據(jù)
查詢數(shù)據(jù),游標(biāo)對(duì)象提供了 fetchall() 和 fetchone() 方法。fetchall() 方法獲取所有數(shù)據(jù),返回一個(gè)列表。fetchone() 方法獲取其中一個(gè)結(jié)果,返回一個(gè)元組。
【示例】fetchall() 查詢所有數(shù)據(jù)
# 導(dǎo)入 sqllite3 模塊
import sqlite3
# 硬盤上創(chuàng)建連接
con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
# 獲取 cursor 對(duì)象
cur = con.cursor()
# 創(chuàng)建查詢SQL語(yǔ)句
sql = 'SELECT * FROM t_person'
try:
cur.execute(sql)
# 獲取所有數(shù)據(jù)
person_all = cur.fetchall()
# person = cur.fetchone() 獲取一條數(shù)據(jù)
# print(person_all)
# 遍歷
for p in person_all:
print(p)
except Exception as e:
print(e)
print('查詢失敗')
finally:
# 關(guān)閉游標(biāo)
cur.close()
# 關(guān)閉連接
con.close()使用IPython測(cè)試:
In [1]: import sqlite3
In [2]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
In [3]: cur = con.cursor()
In [4]: sql = 'SELECT * FROM t_person';
In [5]: try:
...: cur.execute(sql)
...: person_all = cur.fetchall()
...: for p in person_all:
...: print(p)
...: except Exception as e:
...: print(e)
...: print('acquire failed')
...: finally:
...: cur.close()
...: con.close()
...:
(1, 'XRR', 28)
(2, 'XFS', 25)
(3, 'XPS', 21)
(4, 'XRD', 30)使用 SQLite3 修改數(shù)據(jù)
# 導(dǎo)入 sqllite3 模塊
import sqlite3
# 硬盤上創(chuàng)建連接
con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
# 獲取 cursor 對(duì)象
cur = con.cursor()
# 構(gòu)造更新數(shù)據(jù)的sql語(yǔ)句
update_sql = 'update t_person set pname=? where pno=?'
try:
cur.execute(update_sql, ('ABC', 1))
# 提交事務(wù)
con.commit()
print('修改成功')
except Exception as e:
print(e)
print('修改失敗')
con.rollback()
finally:
cur.close()
con.close()IPython中測(cè)試修改:
In [6]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
In [7]: cur = con.cursor()
In [8]: update_sql = 'UPDATE t_person SET pname=? WHERE pno=?'
In [9]: try:
...: cur.execute(update_sql, ('ABC', 1))
...: con.commit()
...: print('Modify Successfully')
...: except Exception as e:
...: print(e)
...: con.rollback()
...: print('Modify failed')
...: finally:
...: cur.close()
...: con.close()
...:
Modify Successfully使用 SQLite3 刪除數(shù)據(jù)
# 導(dǎo)入 sqllite3 模塊
import sqlite3
# 硬盤上創(chuàng)建連接
con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
# 獲取 cursor 對(duì)象
cur = con.cursor()
# 構(gòu)造更新數(shù)據(jù)的sql語(yǔ)句
delete_sql = 'DELETE FROM t_person where pno=?'
try:
cur.execute(delete_sql, (1,))
# 提交事務(wù)
con.commit()
print('刪除成功')
except Exception as e:
print(e)
print('刪除失敗')
con.rollback()
finally:
cur.close()
con.close()IPython中測(cè)試刪除:
In [14]: con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
In [15]: cur = con.cursor()
In [16]: delete_sql = 'DELETE FROM t_person WHERE pno=?'
In [17]: try:
...: cur.execute(delete_sql, (1,))
...: con.commit()
...: print('DELETE Successfully')
...: except Exception as e:
...: print(e)
...: print('DELETE failed')
...: con.rollback()
...: finally:
...: cur.close()
...: con.close()
...:
DELETE Successfully到此這篇關(guān)于Python 操作SQLite3數(shù)據(jù)庫(kù)的文章就介紹到這了,更多相關(guān)Python 操作SQLite3內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
對(duì)Python發(fā)送帶header的http請(qǐng)求方法詳解
今天小編就為大家分享一篇對(duì)Python發(fā)送帶header的http請(qǐng)求方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
python實(shí)現(xiàn)aes加密及pycryptodome庫(kù)使用
AES算法是高級(jí)加密標(biāo)準(zhǔn),它是一種對(duì)稱加密算法,AES只有一個(gè)密鑰,這個(gè)密鑰既用來(lái)加密,也用于解密,這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)aes加密及pycryptodome庫(kù)使用的相關(guān)資料,需要的朋友可以參考下2023-10-10
Python的爬蟲(chóng)程序編寫(xiě)框架Scrapy入門學(xué)習(xí)教程
Python的一大優(yōu)勢(shì)就是可以輕松制作Web爬蟲(chóng),而超高人氣的Scrapy則是名副其實(shí)的Python編寫(xiě)爬蟲(chóng)的利器,這里我們就來(lái)看一下Python的爬蟲(chóng)程序編寫(xiě)框架Scrapy入門學(xué)習(xí)教程:2016-07-07
Python中文件常用操作的完整代碼(零基礎(chǔ)就能上手)
文件是存儲(chǔ)在磁盤上的數(shù)據(jù)集合,通過(guò)文件名進(jìn)行標(biāo)識(shí),Python程序需要先建立與磁盤文件的通道才能讀取或?qū)懭霐?shù)據(jù),本文將和大家詳細(xì)介紹了Python中文件的一些常用操作,希望對(duì)大家有所幫助2026-06-06
Python實(shí)現(xiàn)基于TCP UDP協(xié)議的IPv4 IPv6模式客戶端和服務(wù)端功能示例
這篇文章主要介紹了Python實(shí)現(xiàn)基于TCP UDP協(xié)議的IPv4 IPv6模式客戶端和服務(wù)端功能,結(jié)合實(shí)例形式分析了Python基于TCP UDP協(xié)議的IPv4 IPv6模式客戶端和服務(wù)端數(shù)據(jù)發(fā)送與接收相關(guān)操作技巧,需要的朋友可以參考下2018-03-03
python在Windows下安裝setuptools(easy_install工具)步驟詳解
這篇文章主要介紹了python在Windows下安裝setuptools(easy_install工具)步驟,簡(jiǎn)單介紹了setuptools并分析了其安裝步驟與所涉及的相關(guān)軟件,需要的朋友可以參考下2016-07-07

