Python開發(fā)SQLite3數(shù)據(jù)庫相關(guān)操作詳解【連接,查詢,插入,更新,刪除,關(guān)閉等】
本文實例講述了Python開發(fā)SQLite3數(shù)據(jù)庫相關(guān)操作。分享給大家供大家參考,具體如下:
'''SQLite數(shù)據(jù)庫是一款非常小巧的嵌入式開源數(shù)據(jù)庫軟件,也就是說
沒有獨立的維護進程,所有的維護都來自于程序本身。
在python中,使用sqlite3創(chuàng)建數(shù)據(jù)庫的連接,當(dāng)我們指定的數(shù)據(jù)庫文件不存在的時候
連接對象會自動創(chuàng)建數(shù)據(jù)庫文件;如果數(shù)據(jù)庫文件已經(jīng)存在,則連接對象不會再創(chuàng)建
數(shù)據(jù)庫文件,而是直接打開該數(shù)據(jù)庫文件。
連接對象可以是硬盤上面的數(shù)據(jù)庫文件,也可以是建立在內(nèi)存中的,在內(nèi)存中的數(shù)據(jù)庫
執(zhí)行完任何操作后,都不需要提交事務(wù)的(commit)
創(chuàng)建在硬盤上面: conn = sqlite3.connect('c:\\test\\test.db')
創(chuàng)建在內(nèi)存上面: conn = sqlite3.connect('"memory:')
下面我們一硬盤上面創(chuàng)建數(shù)據(jù)庫文件為例來具體說明:
conn = sqlite3.connect('c:\\test\\hongten.db')
其中conn對象是數(shù)據(jù)庫鏈接對象,而對于數(shù)據(jù)庫鏈接對象來說,具有以下操作:
commit() --事務(wù)提交
rollback() --事務(wù)回滾
close() --關(guān)閉一個數(shù)據(jù)庫鏈接
cursor() --創(chuàng)建一個游標
cu = conn.cursor()
這樣我們就創(chuàng)建了一個游標對象:cu
在sqlite3中,所有sql語句的執(zhí)行都要在游標對象的參與下完成
對于游標對象cu,具有以下具體操作:
execute() --執(zhí)行一條sql語句
executemany() --執(zhí)行多條sql語句
close() --游標關(guān)閉
fetchone() --從結(jié)果中取出一條記錄
fetchmany() --從結(jié)果中取出多條記錄
fetchall() --從結(jié)果中取出所有記錄
scroll() --游標滾動
'''
下面是我做的demo,在demo中,我做了很詳細的注釋和功能的演示,詳情如下:
當(dāng)SHOW_SQL = False的時候:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> show_sql : False 刪除數(shù)據(jù)庫表測試... 硬盤上面:[c:\test\hongten.db] 刪除數(shù)據(jù)庫表[student]成功! 創(chuàng)建數(shù)據(jù)庫表測試... 硬盤上面:[c:\test\hongten.db] 創(chuàng)建數(shù)據(jù)庫表[student]成功! 保存數(shù)據(jù)測試... 硬盤上面:[c:\test\hongten.db] 查詢所有數(shù)據(jù)... 硬盤上面:[c:\test\hongten.db] (1, 'Hongten', '男', 20, '廣東省廣州市', '13423****62') (2, 'Tom', '男', 22, '美國舊金山', '15423****63') (3, 'Jake', '女', 18, '廣東省廣州市', '18823****87') (4, 'Cate', '女', 21, '廣東省廣州市', '14323****32') ################################################## 查詢一條數(shù)據(jù)... 硬盤上面:[c:\test\hongten.db] (1, 'Hongten', '男', 20, '廣東省廣州市', '13423****62') ################################################## 更新數(shù)據(jù)... 硬盤上面:[c:\test\hongten.db] 查詢所有數(shù)據(jù)... 硬盤上面:[c:\test\hongten.db] (1, 'HongtenAA', '男', 20, '廣東省廣州市', '13423****62') (2, 'HongtenBB', '男', 22, '美國舊金山', '15423****63') (3, 'HongtenCC', '女', 18, '廣東省廣州市', '18823****87') (4, 'HongtenDD', '女', 21, '廣東省廣州市', '14323****32') ################################################## 刪除數(shù)據(jù)... 硬盤上面:[c:\test\hongten.db] 查詢所有數(shù)據(jù)... 硬盤上面:[c:\test\hongten.db] (2, 'HongtenBB', '男', 22, '美國舊金山', '15423****63') (4, 'HongtenDD', '女', 21, '廣東省廣州市', '14323****32') >>>
當(dāng)SHOW_SQL = True的時候:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
show_sql : True
刪除數(shù)據(jù)庫表測試...
硬盤上面:[c:\test\hongten.db]
執(zhí)行sql:[DROP TABLE IF EXISTS student]
刪除數(shù)據(jù)庫表[student]成功!
創(chuàng)建數(shù)據(jù)庫表測試...
硬盤上面:[c:\test\hongten.db]
執(zhí)行sql:[CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`gender` varchar(4) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
)]
創(chuàng)建數(shù)據(jù)庫表[student]成功!
保存數(shù)據(jù)測試...
硬盤上面:[c:\test\hongten.db]
執(zhí)行sql:[INSERT INTO student values (?, ?, ?, ?, ?, ?)],參數(shù):[(1, 'Hongten', '男', 20, '廣東省廣州市', '13423****62')]
執(zhí)行sql:[INSERT INTO student values (?, ?, ?, ?, ?, ?)],參數(shù):[(2, 'Tom', '男', 22, '美國舊金山', '15423****63')]
執(zhí)行sql:[INSERT INTO student values (?, ?, ?, ?, ?, ?)],參數(shù):[(3, 'Jake', '女', 18, '廣東省廣州市', '18823****87')]
執(zhí)行sql:[INSERT INTO student values (?, ?, ?, ?, ?, ?)],參數(shù):[(4, 'Cate', '女', 21, '廣東省廣州市', '14323****32')]
查詢所有數(shù)據(jù)...
硬盤上面:[c:\test\hongten.db]
執(zhí)行sql:[SELECT * FROM student]
(1, 'Hongten', '男', 20, '廣東省廣州市', '13423****62')
(2, 'Tom', '男', 22, '美國舊金山', '15423****63')
(3, 'Jake', '女', 18, '廣東省廣州市', '18823****87')
(4, 'Cate', '女', 21, '廣東省廣州市', '14323****32')
##################################################
查詢一條數(shù)據(jù)...
硬盤上面:[c:\test\hongten.db]
執(zhí)行sql:[SELECT * FROM student WHERE ID = ? ],參數(shù):[1]
(1, 'Hongten', '男', 20, '廣東省廣州市', '13423****62')
##################################################
更新數(shù)據(jù)...
硬盤上面:[c:\test\hongten.db]
執(zhí)行sql:[UPDATE student SET name = ? WHERE ID = ? ],參數(shù):[('HongtenAA', 1)]
執(zhí)行sql:[UPDATE student SET name = ? WHERE ID = ? ],參數(shù):[('HongtenBB', 2)]
執(zhí)行sql:[UPDATE student SET name = ? WHERE ID = ? ],參數(shù):[('HongtenCC', 3)]
執(zhí)行sql:[UPDATE student SET name = ? WHERE ID = ? ],參數(shù):[('HongtenDD', 4)]
查詢所有數(shù)據(jù)...
硬盤上面:[c:\test\hongten.db]
執(zhí)行sql:[SELECT * FROM student]
(1, 'HongtenAA', '男', 20, '廣東省廣州市', '13423****62')
(2, 'HongtenBB', '男', 22, '美國舊金山', '15423****63')
(3, 'HongtenCC', '女', 18, '廣東省廣州市', '18823****87')
(4, 'HongtenDD', '女', 21, '廣東省廣州市', '14323****32')
##################################################
刪除數(shù)據(jù)...
硬盤上面:[c:\test\hongten.db]
執(zhí)行sql:[DELETE FROM student WHERE NAME = ? AND ID = ? ],參數(shù):[('HongtenAA', 1)]
執(zhí)行sql:[DELETE FROM student WHERE NAME = ? AND ID = ? ],參數(shù):[('HongtenCC', 3)]
查詢所有數(shù)據(jù)...
硬盤上面:[c:\test\hongten.db]
執(zhí)行sql:[SELECT * FROM student]
(2, 'HongtenBB', '男', 22, '美國舊金山', '15423****63')
(4, 'HongtenDD', '女', 21, '廣東省廣州市', '14323****32')
>>>
具體代碼:
#python sqlite
#Author : Hongten
#Create : 2013-08-09
#Version: 1.0
#DB-API 2.0 interface for SQLite databases
import sqlite3
import os
'''SQLite數(shù)據(jù)庫是一款非常小巧的嵌入式開源數(shù)據(jù)庫軟件,也就是說
沒有獨立的維護進程,所有的維護都來自于程序本身。
在python中,使用sqlite3創(chuàng)建數(shù)據(jù)庫的連接,當(dāng)我們指定的數(shù)據(jù)庫文件不存在的時候
連接對象會自動創(chuàng)建數(shù)據(jù)庫文件;如果數(shù)據(jù)庫文件已經(jīng)存在,則連接對象不會再創(chuàng)建
數(shù)據(jù)庫文件,而是直接打開該數(shù)據(jù)庫文件。
連接對象可以是硬盤上面的數(shù)據(jù)庫文件,也可以是建立在內(nèi)存中的,在內(nèi)存中的數(shù)據(jù)庫
執(zhí)行完任何操作后,都不需要提交事務(wù)的(commit)
創(chuàng)建在硬盤上面: conn = sqlite3.connect('c:\\test\\test.db')
創(chuàng)建在內(nèi)存上面: conn = sqlite3.connect('"memory:')
下面我們一硬盤上面創(chuàng)建數(shù)據(jù)庫文件為例來具體說明:
conn = sqlite3.connect('c:\\test\\hongten.db')
其中conn對象是數(shù)據(jù)庫鏈接對象,而對于數(shù)據(jù)庫鏈接對象來說,具有以下操作:
commit() --事務(wù)提交
rollback() --事務(wù)回滾
close() --關(guān)閉一個數(shù)據(jù)庫鏈接
cursor() --創(chuàng)建一個游標
cu = conn.cursor()
這樣我們就創(chuàng)建了一個游標對象:cu
在sqlite3中,所有sql語句的執(zhí)行都要在游標對象的參與下完成
對于游標對象cu,具有以下具體操作:
execute() --執(zhí)行一條sql語句
executemany() --執(zhí)行多條sql語句
close() --游標關(guān)閉
fetchone() --從結(jié)果中取出一條記錄
fetchmany() --從結(jié)果中取出多條記錄
fetchall() --從結(jié)果中取出所有記錄
scroll() --游標滾動
'''
#global var
#數(shù)據(jù)庫文件絕句路徑
DB_FILE_PATH = ''
#表名稱
TABLE_NAME = ''
#是否打印sql
SHOW_SQL = True
def get_conn(path):
'''獲取到數(shù)據(jù)庫的連接對象,參數(shù)為數(shù)據(jù)庫文件的絕對路徑
如果傳遞的參數(shù)是存在,并且是文件,那么就返回硬盤上面改
路徑下的數(shù)據(jù)庫文件的連接對象;否則,返回內(nèi)存中的數(shù)據(jù)接
連接對象'''
conn = sqlite3.connect(path)
if os.path.exists(path) and os.path.isfile(path):
print('硬盤上面:[{}]'.format(path))
return conn
else:
conn = None
print('內(nèi)存上面:[:memory:]')
return sqlite3.connect(':memory:')
def get_cursor(conn):
'''該方法是獲取數(shù)據(jù)庫的游標對象,參數(shù)為數(shù)據(jù)庫的連接對象
如果數(shù)據(jù)庫的連接對象不為None,則返回數(shù)據(jù)庫連接對象所創(chuàng)
建的游標對象;否則返回一個游標對象,該對象是內(nèi)存中數(shù)據(jù)
庫連接對象所創(chuàng)建的游標對象'''
if conn is not None:
return conn.cursor()
else:
return get_conn('').cursor()
###############################################################
#### 創(chuàng)建|刪除表操作 START
###############################################################
def drop_table(conn, table):
'''如果表存在,則刪除表,如果表中存在數(shù)據(jù)的時候,使用該
方法的時候要慎用!'''
if table is not None and table != '':
sql = 'DROP TABLE IF EXISTS ' + table
if SHOW_SQL:
print('執(zhí)行sql:[{}]'.format(sql))
cu = get_cursor(conn)
cu.execute(sql)
conn.commit()
print('刪除數(shù)據(jù)庫表[{}]成功!'.format(table))
close_all(conn, cu)
else:
print('the [{}] is empty or equal None!'.format(sql))
def create_table(conn, sql):
'''創(chuàng)建數(shù)據(jù)庫表:student'''
if sql is not None and sql != '':
cu = get_cursor(conn)
if SHOW_SQL:
print('執(zhí)行sql:[{}]'.format(sql))
cu.execute(sql)
conn.commit()
print('創(chuàng)建數(shù)據(jù)庫表[student]成功!')
close_all(conn, cu)
else:
print('the [{}] is empty or equal None!'.format(sql))
###############################################################
#### 創(chuàng)建|刪除表操作 END
###############################################################
def close_all(conn, cu):
'''關(guān)閉數(shù)據(jù)庫游標對象和數(shù)據(jù)庫連接對象'''
try:
if cu is not None:
cu.close()
finally:
if cu is not None:
cu.close()
###############################################################
#### 數(shù)據(jù)庫操作CRUD START
###############################################################
def save(conn, sql, data):
'''插入數(shù)據(jù)'''
if sql is not None and sql != '':
if data is not None:
cu = get_cursor(conn)
for d in data:
if SHOW_SQL:
print('執(zhí)行sql:[{}],參數(shù):[{}]'.format(sql, d))
cu.execute(sql, d)
conn.commit()
close_all(conn, cu)
else:
print('the [{}] is empty or equal None!'.format(sql))
def fetchall(conn, sql):
'''查詢所有數(shù)據(jù)'''
if sql is not None and sql != '':
cu = get_cursor(conn)
if SHOW_SQL:
print('執(zhí)行sql:[{}]'.format(sql))
cu.execute(sql)
r = cu.fetchall()
if len(r) > 0:
for e in range(len(r)):
print(r[e])
else:
print('the [{}] is empty or equal None!'.format(sql))
def fetchone(conn, sql, data):
'''查詢一條數(shù)據(jù)'''
if sql is not None and sql != '':
if data is not None:
#Do this instead
d = (data,)
cu = get_cursor(conn)
if SHOW_SQL:
print('執(zhí)行sql:[{}],參數(shù):[{}]'.format(sql, data))
cu.execute(sql, d)
r = cu.fetchall()
if len(r) > 0:
for e in range(len(r)):
print(r[e])
else:
print('the [{}] equal None!'.format(data))
else:
print('the [{}] is empty or equal None!'.format(sql))
def update(conn, sql, data):
'''更新數(shù)據(jù)'''
if sql is not None and sql != '':
if data is not None:
cu = get_cursor(conn)
for d in data:
if SHOW_SQL:
print('執(zhí)行sql:[{}],參數(shù):[{}]'.format(sql, d))
cu.execute(sql, d)
conn.commit()
close_all(conn, cu)
else:
print('the [{}] is empty or equal None!'.format(sql))
def delete(conn, sql, data):
'''刪除數(shù)據(jù)'''
if sql is not None and sql != '':
if data is not None:
cu = get_cursor(conn)
for d in data:
if SHOW_SQL:
print('執(zhí)行sql:[{}],參數(shù):[{}]'.format(sql, d))
cu.execute(sql, d)
conn.commit()
close_all(conn, cu)
else:
print('the [{}] is empty or equal None!'.format(sql))
###############################################################
#### 數(shù)據(jù)庫操作CRUD END
###############################################################
###############################################################
#### 測試操作 START
###############################################################
def drop_table_test():
'''刪除數(shù)據(jù)庫表測試'''
print('刪除數(shù)據(jù)庫表測試...')
conn = get_conn(DB_FILE_PATH)
drop_table(conn, TABLE_NAME)
def create_table_test():
'''創(chuàng)建數(shù)據(jù)庫表測試'''
print('創(chuàng)建數(shù)據(jù)庫表測試...')
create_table_sql = '''CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`gender` varchar(4) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
)'''
conn = get_conn(DB_FILE_PATH)
create_table(conn, create_table_sql)
def save_test():
'''保存數(shù)據(jù)測試...'''
print('保存數(shù)據(jù)測試...')
save_sql = '''INSERT INTO student values (?, ?, ?, ?, ?, ?)'''
data = [(1, 'Hongten', '男', 20, '廣東省廣州市', '13423****62'),
(2, 'Tom', '男', 22, '美國舊金山', '15423****63'),
(3, 'Jake', '女', 18, '廣東省廣州市', '18823****87'),
(4, 'Cate', '女', 21, '廣東省廣州市', '14323****32')]
conn = get_conn(DB_FILE_PATH)
save(conn, save_sql, data)
def fetchall_test():
'''查詢所有數(shù)據(jù)...'''
print('查詢所有數(shù)據(jù)...')
fetchall_sql = '''SELECT * FROM student'''
conn = get_conn(DB_FILE_PATH)
fetchall(conn, fetchall_sql)
def fetchone_test():
'''查詢一條數(shù)據(jù)...'''
print('查詢一條數(shù)據(jù)...')
fetchone_sql = 'SELECT * FROM student WHERE ID = ? '
data = 1
conn = get_conn(DB_FILE_PATH)
fetchone(conn, fetchone_sql, data)
def update_test():
'''更新數(shù)據(jù)...'''
print('更新數(shù)據(jù)...')
update_sql = 'UPDATE student SET name = ? WHERE ID = ? '
data = [('HongtenAA', 1),
('HongtenBB', 2),
('HongtenCC', 3),
('HongtenDD', 4)]
conn = get_conn(DB_FILE_PATH)
update(conn, update_sql, data)
def delete_test():
'''刪除數(shù)據(jù)...'''
print('刪除數(shù)據(jù)...')
delete_sql = 'DELETE FROM student WHERE NAME = ? AND ID = ? '
data = [('HongtenAA', 1),
('HongtenCC', 3)]
conn = get_conn(DB_FILE_PATH)
delete(conn, delete_sql, data)
###############################################################
#### 測試操作 END
###############################################################
def init():
'''初始化方法'''
#數(shù)據(jù)庫文件絕句路徑
global DB_FILE_PATH
DB_FILE_PATH = 'c:\\test\\hongten.db'
#數(shù)據(jù)庫表名稱
global TABLE_NAME
TABLE_NAME = 'student'
#是否打印sql
global SHOW_SQL
SHOW_SQL = True
print('show_sql : {}'.format(SHOW_SQL))
#如果存在數(shù)據(jù)庫表,則刪除表
drop_table_test()
#創(chuàng)建數(shù)據(jù)庫表student
create_table_test()
#向數(shù)據(jù)庫表中插入數(shù)據(jù)
save_test()
def main():
init()
fetchall_test()
print('#' * 50)
fetchone_test()
print('#' * 50)
update_test()
fetchall_test()
print('#' * 50)
delete_test()
fetchall_test()
if __name__ == '__main__':
main()
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python按順序重命名文件并分類轉(zhuǎn)移到各個文件夾中的實現(xiàn)代碼
這篇文章主要介紹了python按順序重命名文件并分類轉(zhuǎn)移到各個文件夾中,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
Python中調(diào)用和運行其他.py文件的多種實現(xiàn)方法
本文介紹了在Python中調(diào)用和運行其他.py文件的四種方法:subprocess模塊、exec函數(shù)、import語句和os.system函數(shù),每種方法都有其適用場景和優(yōu)缺點2025-02-02
Pycharm學(xué)習(xí)教程(4) Python解釋器的相關(guān)配置
這篇文章主要為大家詳細介紹了最全的Pycharm學(xué)習(xí)教程第四篇,Python解釋器配置,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
Python數(shù)據(jù)分析numpy文本數(shù)據(jù)讀取索引切片實例詳解
這篇文章主要為大家介紹了Python數(shù)據(jù)分析numpy文本數(shù)據(jù)讀取索引切片實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08

