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

yipeiwu_com6年前Python基础

本文实例讲述了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数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

flask-socketio实现WebSocket的方法

【flask-socektio】 之前不知道在哪个场合下提到过如何从web后台向前台推送消息。听闻了反向ajax技术这种模式之后,大呼神奇,试了一下之后发现也确实可以用。不过,反向aj...

Python pandas实现excel工作表合并功能详解

Python pandas实现excel工作表合并功能详解

import os,pandas as pd,re #1.获取文件夹下要合并的文件名 dirpath = '文件夹地址' #工作表3特殊处理 需要开始下标和结束下标 begin =...

python2和python3实现在图片上加汉字的方法

python2和python3实现在图片上加汉字的方法

python2和python3实现在图片上加汉字,最主要的区别还是内部编码方式不一样导致的,在代码上表现为些许的差别。理解了内部编码原理也就不会遇到这些问题了,以下代码是在WIN10系统...

利用python对Excel中的特定数据提取并写入新表的方法

最近刚开始学python,正好实习工作中遇到对excel中的数据进行处理的问题,就想到利用python来解决,也恰好练手。 实际的问题是要从excel表中提取日期、邮件地址和时间,然后统...

pytorch:实现简单的GAN示例(MNIST数据集)

我就废话不多说了,直接上代码吧! # -*- coding: utf-8 -*- """ Created on Sat Oct 13 10:22:45 2018 @author: w...