Python SQLite入门教程:轻量级数据库操作指南 | Python数据库编程
- Python
- 2025-08-02
- 1469
Python SQLite入门教程:轻量级数据库操作指南
SQLite是一个轻量级的嵌入式数据库引擎,不需要独立的服务器进程,非常适合小型应用、移动应用和简单的数据存储需求。Python标准库中的sqlite3模块提供了操作SQLite数据库的接口,无需额外安装。
教程目录
- SQLite简介与优势
- 连接数据库与创建表
- 插入数据操作
- 查询数据与结果处理
- 更新与删除数据
- 事务处理与错误处理
- 完整示例:学生管理系统
1. SQLite简介与优势
SQLite是一个C语言库,实现了自包含、无服务器、零配置的事务型SQL数据库引擎。主要优势包括:
- 轻量级:整个数据库存储在一个文件中,无需单独服务器进程
- 零配置:无需安装或管理,直接使用
- 跨平台:支持所有主流操作系统
- 高性能:在适当场景下性能优于客户端/服务器数据库
Python内置的sqlite3模块提供了符合DB-API 2.0规范的接口,是Python标准库的一部分。
2. 连接数据库与创建表
使用SQLite的第一步是创建数据库连接并建立表结构:
基本步骤:
- 导入sqlite3模块
- 使用connect()方法连接数据库(文件或内存数据库)
- 创建游标对象执行SQL命令
- 执行CREATE TABLE语句创建表
- 提交更改并关闭连接
示例代码:
import sqlite3
# 连接到数据库(如果不存在则创建)
conn = sqlite3.connect('school.db')
# 创建游标对象
cursor = conn.cursor()
# 创建students表
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
grade TEXT
)
''')
# 提交更改
conn.commit()
# 关闭连接
conn.close()
3. 插入数据操作
向SQLite数据库插入数据有多种方式:
单条插入
# 插入单条数据
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
('张三', 18, '高三'))
conn.commit()
多条插入
# 插入多条数据
students = [
('李四', 17, '高二'),
('王五', 19, '高三'),
('赵六', 16, '高一')
]
cursor.executemany("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", students)
conn.commit()
最佳实践:
- 始终使用参数化查询(?占位符)防止SQL注入
- 批量插入时使用executemany()提高性能
- 插入后调用commit()保存更改
4. 查询数据与结果处理
从SQLite数据库检索数据是常见操作,Python提供了多种处理结果的方式。
基本查询方法:
# 查询所有学生
cursor.execute("SELECT * FROM students")
all_students = cursor.fetchall()
# 查询单个学生
cursor.execute("SELECT * FROM students WHERE name=?", ('张三',))
student = cursor.fetchone()
# 查询特定列
cursor.execute("SELECT name, grade FROM students WHERE age >= ?", (18,))
seniors = cursor.fetchall()
结果处理方式
fetchone():获取下一行fetchmany(size):获取指定数量的行fetchall():获取所有结果- 直接遍历游标对象
结果遍历示例
cursor.execute("SELECT id, name, age FROM students")
for row in cursor:
print(f"ID: {row[0]}, 姓名: {row[1]}, 年龄: {row[2]}")
5. 更新与删除数据
修改和删除数据的操作同样重要:
更新数据
# 更新学生信息
cursor.execute("""
UPDATE students
SET age = ?, grade = ?
WHERE name = ?
""", (19, '毕业班', '张三'))
# 检查受影响的行数
print(f"更新了 {cursor.rowcount} 条记录")
conn.commit()
删除数据
# 删除记录
cursor.execute("DELETE FROM students WHERE id = ?", (5,))
# 使用rowcount确认删除
if cursor.rowcount > 0:
print("删除成功")
else:
print("未找到该ID的学生")
conn.commit()
注意事项:
- UPDATE和DELETE操作必须谨慎,先SELECT确认目标数据
- WHERE子句应尽可能具体,避免意外修改
- 操作后使用rowcount属性检查受影响的行数
- 重要操作前备份数据库
6. 事务处理与错误处理
事务管理对于数据库操作至关重要,可确保数据一致性。
使用事务
try:
# 开始事务(默认已开始)
cursor.execute("BEGIN TRANSACTION")
# 执行多个操作
cursor.execute("INSERT INTO students (...) VALUES (...)")
cursor.execute("UPDATE students SET ... WHERE ...")
# 提交事务
conn.commit()
except sqlite3.Error as e:
# 发生错误时回滚
conn.rollback()
print(f"数据库错误: {e}")
finally:
# 确保连接关闭
conn.close()
使用上下文管理器
with sqlite3.connect('school.db') as conn:
cursor = conn.cursor()
cursor.execute(...)
# 自动提交或回滚
# 自动关闭连接
上下文管理器简化了资源管理,确保连接正确关闭。
常见错误类型
sqlite3.OperationalError:SQL操作错误sqlite3.IntegrityError:数据完整性错误sqlite3.ProgrammingError:编程错误sqlite3.DatabaseError:数据库相关错误
7. 完整示例:学生管理系统
以下是一个使用SQLite的简单学生管理系统:
import sqlite3
class StudentManager:
def __init__(self, db_name='students.db'):
self.conn = sqlite3.connect(db_name)
self.cursor = self.conn.cursor()
self._create_table()
def _create_table(self):
"""创建学生表"""
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
self.conn.commit()
def add_student(self, name, age, grade):
"""添加学生"""
try:
self.cursor.execute(
"INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
(name, age, grade)
self.conn.commit()
print(f"学生 {name} 添加成功!")
return self.cursor.lastrowid
except sqlite3.Error as e:
print(f"添加学生失败: {e}")
return None
def get_all_students(self):
"""获取所有学生"""
self.cursor.execute("SELECT * FROM students")
return self.cursor.fetchall()
def update_student_grade(self, student_id, new_grade):
"""更新学生年级"""
try:
self.cursor.execute(
"UPDATE students SET grade = ? WHERE id = ?",
(new_grade, student_id)
)
if self.cursor.rowcount == 0:
print(f"未找到ID为 {student_id} 的学生")
return False
self.conn.commit()
print("更新成功!")
return True
except sqlite3.Error as e:
print(f"更新失败: {e}")
return False
def delete_student(self, student_id):
"""删除学生"""
try:
self.cursor.execute(
"DELETE FROM students WHERE id = ?",
(student_id,)
)
if self.cursor.rowcount == 0:
print(f"未找到ID为 {student_id} 的学生")
return False
self.conn.commit()
print("删除成功!")
return True
except sqlite3.Error as e:
print(f"删除失败: {e}")
return False
def close(self):
"""关闭数据库连接"""
self.conn.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
# 使用示例
if __name__ == "__main__":
with StudentManager() as manager:
# 添加学生
manager.add_student("张三", 18, "高三")
manager.add_student("李四", 17, "高二")
# 获取所有学生
print("所有学生:")
for student in manager.get_all_students():
print(student)
# 更新学生信息
manager.update_student_grade(1, "毕业班")
# 删除学生
manager.delete_student(2)
总结
SQLite作为轻量级数据库解决方案,结合Python的sqlite3模块,为开发者提供了简单高效的本地数据存储能力。本教程涵盖了:
- SQLite数据库连接与表创建
- 数据插入、查询、更新和删除操作
- 事务管理与错误处理最佳实践
- 完整的应用示例
对于需要简单数据存储的应用场景,SQLite是一个理想的选择。对于更复杂的应用,可以考虑使用SQLAlchemy等ORM工具。
本文由YuanLanYan于2025-08-02发表在吾爱品聚,如有疑问,请联系我们。
本文链接:http://pjw.521pj.cn/20257149.html
发表评论