Python轻量级ORM框架Peewee访问sqlite数据库的方法详解

程一诺
程一诺
发布时间:2026-10-13| 2人浏览过
原创

本文详细介绍Python轻量级ORM框架Peewee在SQLite数据库中的使用方法。内容涵盖ORM基本概念、Peewee的安装步骤、模型类定义(表到类的映射)、表的创建与数据增删改查操作,以及复杂查询技巧。通过具体代码示例,帮助开发者快速掌握使用Peewee进行数据库交互的核心技能。

本文通过具体实例,解析如何利用Python轻量级ORM框架Peewee来操作SQLite数据库,旨在为读者提供实用的参考指南。

ORM(Object Relation Model,对象关系模型)的核心作用是将数据库中的表映射为面向对象编程语言中的类。借助ORM,开发者无需编写SQL语句,直接通过操作对象即可完成数据的增删改查。

ORM技术主要包含以下三种基本机制:

(1)映射技术

数据类型映射:将数据库中的数据类型转换为编程语言中对应的数据类型,例如将数据库的int类型映射为Python的integer类型。 类映射:将数据库表映射为编程语言的类,从而避免编写SQL,直接操作对象。 关系映射:针对关系型数据库中通过主外键建立的实体关联,将其映射为编程语言中基于对象引用的连接关系。

(2)CURD技术

CURD代表Create(增加)、Update(更新)、Retrieve(检索)和Delete(删除),即实现了数据库的基本增删改查功能。

(3)缓存技术

将数据库查询结果以类对象形式存储于内存中,以便后续随时提取使用。

在ORM查询命令执行阶段,系统并不会立即访问数据库;只有当真正需要读取数据时,才会向数据库发起查询请求。

一、安装peewee

c:\Python27\Scripts>pip install peewee
Collecting peewee
 Downloading peewee-2.8.5.tar.gz (506kB)
  100% |████████████████████████████████| 512kB 437kB/s
Installing collected packages: peewee
 Running setup.py install for peewee ... done
Successfully installed peewee-2.8.5

二、定义表到类的映射

首先将数据表定义为类,并保存为orm.py模块,后续代码将引用该模块。

具体代码实现如下:

# -*- coding:utf8 -*-
from peewee import *
db = SqliteDatabase('test.db')
class BaseModel(Model):
  class Meta:
    database = db
class Course(BaseModel):
  id = PrimaryKeyField()
  title = CharField(null = False)
  period = IntegerField()
  description = CharField()
  class Meta:
    order_by = ('title',)
    db_table = 'course'
class Teacher(BaseModel):
  id = PrimaryKeyField()
  name = CharField(null = False)
  gender = BooleanField()
  address = CharField()
  course_id = ForeignKeyField(Course,to_field='id',related_name = "course")
  class Meta:
    order_by = ('name',)
    db_table = 'teacher'

三、创建表、新增记录

# -*- coding:utf8 -*-
from orm import *
Course.create_table()
Teacher.create_table()
Course.create(id = 1,title='经济学',period = 320,description='文科必修')
Course.create(id = 2,title='大学语文',period = 300,description='所有学科必修')
Course.create(id = 3,title='操作系统',period = 320,description='计算机必修')
Course.create(id = 4,title='马克思主义哲学',period = 320,description='必修')
Teacher.create(id = 1,name = '张三',gender=True,address='...',course_id = 1)
Teacher.create(id = 2,name = '李四',gender=False,address='-',course_id = 2)
Teacher.create(id = 3,name = '王五',gender=True,address='=',course_id = 3)

四、更复杂的操作

# -*- coding:gbk -*-
from orm import *
#获取1行数据
record = Course.get(Course.title=='大学语文')
print("课程:%s ,学时: %d" %(record.title,record.period))
#更新这行数据的period字段,保存
record.period = 200
record.save()
print("学分改为:%d" % record.period)
#获取1行数据,再删除,如果不存在,则会报错
record = Course.get(Course.title=='马克思主义哲学')
record.delete_instance()
###查询所有数据
course = Course.select()
###查询符合条件的数据,排序
course = Course.select().where(Course.id <3).order_by(Course.period.desc())
###计算平均值
total = Course.select(fn.Avg(Course.period)).alias('avg_period')
###更新数据
Course.update(period=300).where(Course.id>2).execute()
###关联数据
Record = Course.select().join(Teacher).where(Teacher.gender == True)

操作完成后,可通过命令行执行sqlite3 test.db,然后使用相关命令查看表中的数据。

如需了解更多Python相关内容,可参考本站专题:《Python常见数据库操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》。

希望本文所述内容能对大家的Python程序设计工作有所帮助。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。