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


Posted in Python onJuly 20, 2017

本文实例讲述了Python轻量级ORM框架Peewee访问sqlite数据库的方法。分享给大家供大家参考,具体如下:

ORM框架就是 object relation model,对象关系模型,用来实现把数据库中的表 映射到 面向对象编程语言中的类,不需要写sql,通过操作对象就能实现 增删改查。

ORM的基本技术有3种:

(1)映射技术

数据类型映射:就是把数据库中的数据类型,映射到编程语言中的数据类型。比如,把数据库的int类型映射到Python中的integer 类型。
类映射:把数据库中的表,映射到面向对象编程语言的类,这样就不用写sql,直接操作对象就可以了。
关系映射:关系型数据库最大的特点在于实体之间的关系,也就是表之间通过主外键的设置,产生的关联,把这种关联映射成编程语言中基于对象引用的关系连接。

(2)CURD技术

CURD就是增加、更新、检索、删除的意思,就是实现了数据库中的增删改查的功能。

(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中find()方法的使用
May 18 Python
python利用装饰器进行运算的实例分析
Aug 04 Python
python DataFrame 修改列的顺序实例
Apr 10 Python
Python计算开方、立方、圆周率,精确到小数点后任意位的方法
Jul 17 Python
使用python生成杨辉三角形的示例代码
Aug 29 Python
django+tornado实现实时查看远程日志的方法
Aug 12 Python
Python collections模块使用方法详解
Aug 28 Python
python对Excel按条件进行内容补充(推荐)
Nov 24 Python
python实现飞行棋游戏
Feb 05 Python
opencv 图像礼帽和图像黑帽的实现
Jul 07 Python
如何通过python计算圆周率PI
Nov 11 Python
Python何绘制带有背景色块的折线图
Apr 23 Python
Python函数式编程
Jul 20 #Python
python 换位密码算法的实例详解
Jul 19 #Python
python实现rsa加密实例详解
Jul 19 #Python
Python中标准库OS的常用方法总结大全
Jul 19 #Python
spyder常用快捷键(分享)
Jul 19 #Python
JPype实现在python中调用JAVA的实例
Jul 19 #Python
简单谈谈Python中的json与pickle
Jul 19 #Python
You might like
聊天室php&amp;mysql(六)
2006/10/09 PHP
php下批量挂马和批量清马代码
2011/02/27 PHP
php检测useragent版本示例
2014/03/24 PHP
destoon安全设置中需要设置可写权限的目录及文件
2014/06/21 PHP
php取得字符串首字母的方法
2015/03/25 PHP
PHP MYSQL实现登陆和模糊查询两大功能
2016/02/05 PHP
php通过pecl方式安装扩展的实例讲解
2018/02/02 PHP
PHP多个图片压缩成ZIP的方法
2020/08/18 PHP
js各种验证文本框输入格式(正则表达式)
2010/10/22 Javascript
JavaScript解析json格式数据简单示例
2014/12/09 Javascript
jquery制作LED 时钟特效
2015/02/01 Javascript
javascript实现通过表格绘制颜色填充矩形的方法
2015/04/21 Javascript
angularJs关于指令的一些冷门属性详解
2016/10/24 Javascript
js复制内容到剪贴板代码,js复制代码的简单实例
2016/10/27 Javascript
JS刷新父窗口的几种方式小结(推荐)
2016/11/09 Javascript
javascript容错处理代码(屏蔽js错误)
2017/01/20 Javascript
nodejs使用express创建一个简单web应用
2017/03/31 NodeJs
Three.js的使用及绘制基础3D图形详解
2017/04/27 Javascript
webpack4 配置 ssr 环境遇到“document is not defined”
2019/10/24 Javascript
vue实现抽屉弹窗效果
2020/11/15 Javascript
在Django中编写模版节点及注册标签的方法
2015/07/20 Python
selenium+python实现1688网站验证码图片的截取功能
2018/08/14 Python
在Pandas中给多层索引降级的方法
2018/11/16 Python
Python Unittest原理及基本使用方法
2020/11/06 Python
CSS3 3D旋转rotate效果实例介绍
2016/05/03 HTML / CSS
省优秀教师事迹材料
2014/01/30 职场文书
在校大学生个人的自我评价
2014/02/13 职场文书
经济担保书范文
2014/04/02 职场文书
数控专业毕业生求职信
2014/06/12 职场文书
关于晚自习早退的检讨书
2014/09/13 职场文书
2014年党员自我剖析材料
2014/10/07 职场文书
社区义诊通知
2015/04/24 职场文书
生产车间管理制度
2015/08/04 职场文书
2016年小学生寒假总结
2015/10/10 职场文书
周末问候语大全
2015/11/10 职场文书
总结几个非常实用的Python库
2021/06/26 Python