Python?操作SQLite3數(shù)據(jù)庫的實現(xiàn)示例
從 Python3.x 版本開始,在標(biāo)準庫中已經(jīng)內(nèi)置了 SQLite3 模塊,它可以支持 SQLite3 數(shù)據(jù)庫的訪問和相關(guān)的數(shù)據(jù)庫操作。在需要操作 SQLite3 數(shù)據(jù)庫數(shù)據(jù)時,只須在程序中導(dǎo)入 SQLite3 模塊即可。Python 語言操作 SQLite3 數(shù)據(jù)庫的基本流程如下所示。
(1) 導(dǎo)入相關(guān)庫或模塊(SQLite3)。
(2) 使用 connect() 連接數(shù)據(jù)庫并獲取數(shù)據(jù)庫連接對象。它提供了以下方法:
- .cursor() 方法來創(chuàng)建一個游標(biāo)對象
- .commit() 方法來處理事務(wù)提交
- .rollback() 方法來處理事務(wù)回滾
- .close() 方法來關(guān)閉一個數(shù)據(jù)庫連接
(3) 使用 con.cursor() 獲取游標(biāo)對象。
(4) 使用游標(biāo)對象的方法(execute()、executemany()、fetchall()等)來操作數(shù)據(jù)庫,實現(xiàn)插入、修改和刪除操作,并查詢獲取顯示相關(guān)的記錄。在 Python 程序中,連接函數(shù) sqlite3.connect() 有如下兩個常用參數(shù)。
- database: 表示要訪問的數(shù)據(jù)庫名。
- timeout: 表示訪問數(shù)據(jù)的超時設(shè)定。
(5) 使用 close() 關(guān)閉游標(biāo)對象和數(shù)據(jù)庫連接。數(shù)據(jù)庫操作完成之后,必須及時調(diào)用其 close() 方法關(guān)閉數(shù)據(jù)庫連接,這樣做的目的是減輕數(shù)據(jù)庫服務(wù)器的壓力。
使用 SQLite3 創(chuàng)建表
使用 sqlite3 模塊的 connect 方法來創(chuàng)建/打開數(shù)據(jù)庫,需要指定數(shù)據(jù)庫路徑,不存在則創(chuàng)建一個新的數(shù)據(jù)庫。
con=sqlite3.connect('/home/blctrl/sqlite-db/first.db')下面實例代碼演示使用 SQLite3 創(chuàng)建數(shù)據(jù)庫的過程。
# 導(dǎo)入 sqlite3 模塊
import sqlite3
# 1.硬盤上創(chuàng)建連接
con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
# 獲取 cursor 對象
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下測試:
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)對象的 execute 執(zhí)行插入的 sql,使用 executemany() 執(zhí)行多條 sql 語句,使用 executemany()比循環(huán)使用execute()執(zhí)行多條sql語句效率高.
示例: 使用SQLite3插入一條數(shù)據(jù)
# 導(dǎo)入 sqllite3 模塊
import sqlite3
# 硬盤上創(chuàng)建連接
con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
# 獲取 cursor 對象
cur = con.cursor()
# 構(gòu)造sql插入語句
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中進行單條數(shù)據(jù)插入的測試:
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中進行多條數(shù)據(jù)插入的測試:
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)對象提供了 fetchall() 和 fetchone() 方法。fetchall() 方法獲取所有數(shù)據(jù),返回一個列表。fetchone() 方法獲取其中一個結(jié)果,返回一個元組。
【示例】fetchall() 查詢所有數(shù)據(jù)
# 導(dǎo)入 sqllite3 模塊
import sqlite3
# 硬盤上創(chuàng)建連接
con = sqlite3.connect('/home/blctrl/sqlite-db/example.db')
# 獲取 cursor 對象
cur = con.cursor()
# 創(chuàng)建查詢SQL語句
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測試:
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 對象
cur = con.cursor()
# 構(gòu)造更新數(shù)據(jù)的sql語句
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中測試修改:
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 對象
cur = con.cursor()
# 構(gòu)造更新數(shù)據(jù)的sql語句
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中測試刪除:
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ù)庫的文章就介紹到這了,更多相關(guān)Python 操作SQLite3內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
對Python發(fā)送帶header的http請求方法詳解
今天小編就為大家分享一篇對Python發(fā)送帶header的http請求方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
python實現(xiàn)aes加密及pycryptodome庫使用
AES算法是高級加密標(biāo)準,它是一種對稱加密算法,AES只有一個密鑰,這個密鑰既用來加密,也用于解密,這篇文章主要給大家介紹了關(guān)于python實現(xiàn)aes加密及pycryptodome庫使用的相關(guān)資料,需要的朋友可以參考下2023-10-10
Python的爬蟲程序編寫框架Scrapy入門學(xué)習(xí)教程
Python的一大優(yōu)勢就是可以輕松制作Web爬蟲,而超高人氣的Scrapy則是名副其實的Python編寫爬蟲的利器,這里我們就來看一下Python的爬蟲程序編寫框架Scrapy入門學(xué)習(xí)教程:2016-07-07
Python中文件常用操作的完整代碼(零基礎(chǔ)就能上手)
文件是存儲在磁盤上的數(shù)據(jù)集合,通過文件名進行標(biāo)識,Python程序需要先建立與磁盤文件的通道才能讀取或?qū)懭霐?shù)據(jù),本文將和大家詳細介紹了Python中文件的一些常用操作,希望對大家有所幫助2026-06-06
Python實現(xiàn)基于TCP UDP協(xié)議的IPv4 IPv6模式客戶端和服務(wù)端功能示例
這篇文章主要介紹了Python實現(xiàn)基于TCP UDP協(xié)議的IPv4 IPv6模式客戶端和服務(wù)端功能,結(jié)合實例形式分析了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工具)步驟,簡單介紹了setuptools并分析了其安裝步驟與所涉及的相關(guān)軟件,需要的朋友可以參考下2016-07-07

