Python SQLite数据库使用示范与性能优化的建议

2024-03-31 00:20

本文主要是介绍Python SQLite数据库使用示范与性能优化的建议,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

创建与关闭

Python SQLite 最基本的建立 DB 数据库连接与关闭 DB 数据库。

下面要建立 tutorial.db 这个 database 连接:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
# ...
con.close()

CREATE 用法

CREATE 语法新建数据表:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
# 新建数据表
cur.execute("CREATE TABLE movie(title, year, score)")
con.commit()
con.close()

INSERT 用法与

SQLite INSERT 语法新增/插入数据:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
cur.execute("INSERT INTO movie VALUES('Monty Python and the Holy Grail', 1975, 8.2),('And Now for Something Completely Different', 1971, 7.5)")
con.commit()  # 记得在执行 INSERT 后提交事务
con.close()

SQLite INSERT 语法插入多笔数据,插入大量多笔数据可使用 cur.executemany(),在 executemany 参数中可以用 ? 表示之后会带入的数据:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
data = [("Monty Python Live at the Hollywood Bowl", 1982, 7.9), ("Monty Python's The Meaning of Life", 1983, 7.5), ("Monty Python's Life of Brian", 1979, 8.0)]
cur.executemany("INSERT INTO movie VALUES(?, ?, ?)", data)
con.commit()  # 记得在执行 INSERT 后提交事务
con.close()

SELECT 用法

SELECT 语法查询数据,如果要查询 tutorial.db 数据库里有什么数据表的话可以使用下面代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
# 查询数据
ret = cur.execute("SELECT name FROM sqlite_master")
print(ret.fetchall())
con.close()

执行结果如下,

['movie',]

如果要查询 movie 数据表里有什么数据的话可以这样写:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
# 查询数据
ret = cur.execute("SELECT * FROM movie")
print(ret.fetchall())
con.close()

执行结果如下,

('Monty Python and the Holy Grail', 1975, 8.2), ('And Now for Something Completely Different', 1971, 7.5), ('Monty Python Live at the Hollywood Bowl', 1982, 7.9), ('Monty Python's The Meaning of Life', 1983, 7.5), ('Monty Python's Life of Brian', 1979, 8.0)

如果要查询 movie 数据表里 score 栏目的话可以这样写:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
# 查询数据
ret = cur.execute("SELECT score FROM movie")
print(ret.fetchall())
con.close()

执行结果如下,

(8.2,), (7.5,), (7.9,), (7.5,), (8.0,)

如果要查询 movie 数据表里 year 跟 title 栏目的话并且按 year 排序的话可以这样写,

上面是示范 fetchall 一次取得所有结果,以下示范用 for 循环来处理 query 每笔结果的数据,

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
for row in cur.execute("SELECT year, title FROM movie ORDER BY year"):print(row)
con.close()

执行结果如下,

(1971, 'And Now for Something Completely Different')
(1975, 'Monty Python and the Holy Grail')
(1979, 'Monty Python's Life of Brian')
(1982, 'Monty Python Live at the Hollywood Bowl')
(1983, 'Monty Python's The Meaning of Life')

SELECT 搭配 WHERE 语法查询特定条件的数据

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
ret = cur.execute("SELECT title, year FROM movie WHERE title='Monty Python and the Holy Grail'")
ret = cur.execute("SELECT title, year FROM movie WHERE year=1971")
print(ret.fetchall())
ret = ret.fetchone()
if ret is None:print("is None")
else:print(ret)
con.close()

执行结果如下,

('Monty Python and the Holy Grail', 1975)

UPDATE 用法

SQLite UPDATE 语法更新数据,如果 movie 数据表找到 score 分数为 8.2 的数据时,更新它们的 title 与 year,

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
cur.execute("UPDATE movie SET title=?, year=? WHERE score=?", ("12345", 2000, 8.2))
con.commit()
con.close()

如果有多笔符合的话会更新多笔。

DELETE 用法

DELETE 语法删除数据表,如果要删除 movie 数据表里的 score 分数为 8.2 的数据可以这么写:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
cur.execute("DELETE FROM movie WHERE score=?", (8.2,))
con.commit()
con.close()

如果要删除 movie 数据表里的所有数据可以这么写:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect("tutorial.db")
cur = con.cursor()
cur.execute("DELETE FROM movie")
con.commit()
con.close()

这篇关于Python SQLite数据库使用示范与性能优化的建议的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/862970

相关文章

使用Python将PDF表格自动提取并写入Word文档表格

《使用Python将PDF表格自动提取并写入Word文档表格》在实际办公与数据处理场景中,PDF文件里的表格往往无法直接复制到Word中,本文将介绍如何使用Python从PDF文件中提取表格数据,并将... 目录引言1. 加载 PDF 文件并准备 Word 文档2. 提取 PDF 表格并创建 Word 表格

使用Python实现局域网远程监控电脑屏幕的方法

《使用Python实现局域网远程监控电脑屏幕的方法》文章介绍了两种使用Python在局域网内实现远程监控电脑屏幕的方法,方法一使用mss和socket,方法二使用PyAutoGUI和Flask,每种方... 目录方法一:使用mss和socket实现屏幕共享服务端(被监控端)客户端(监控端)方法二:使用PyA

Python列表的创建与删除的操作指南

《Python列表的创建与删除的操作指南》列表(list)是Python中最常用、最灵活的内置数据结构之一,它支持动态扩容、混合类型、嵌套结构,几乎无处不在,但你真的会创建和删除列表吗,本文给大家介绍... 目录一、前言二、列表的创建方式1. 字面量语法(最常用)2. 使用list()构造器3. 列表推导式

Python使用Matplotlib和Seaborn绘制常用图表的技巧

《Python使用Matplotlib和Seaborn绘制常用图表的技巧》Python作为数据科学领域的明星语言,拥有强大且丰富的可视化库,其中最著名的莫过于Matplotlib和Seaborn,本篇... 目录1. 引言:数据可视化的力量2. 前置知识与环境准备2.1. 必备知识2.2. 安装所需库2.3

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

Linux内核定时器使用及说明

《Linux内核定时器使用及说明》文章详细介绍了Linux内核定时器的特性、核心数据结构、时间相关转换函数以及操作API,通过示例展示了如何编写和使用定时器,包括按键消抖的应用... 目录1.linux内核定时器特征2.Linux内核定时器核心数据结构3.Linux内核时间相关转换函数4.Linux内核定时

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Python实现快速扫描目标主机的开放端口和服务

《Python实现快速扫描目标主机的开放端口和服务》这篇文章主要为大家详细介绍了如何使用Python编写一个功能强大的端口扫描器脚本,实现快速扫描目标主机的开放端口和服务,感兴趣的小伙伴可以了解下... 目录功能介绍场景应用1. 网络安全审计2. 系统管理维护3. 网络故障排查4. 合规性检查报错处理1.