Peewee 上手

作者: 海上牧云l | 来源:发表于2017-04-01 15:47 被阅读155次

peewee是python编写的ORM,ORM是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换,从效果上说,它其实是创建了一个可在编程语言里使用的--“虚拟对象数据库”,意思就是通过程序语言操作数据库。

peewee提供多种数据库的使用,Sqlite、MySQL、Postgresql。

这里以mysql为例子,介绍一些基本用法。

创建数据库

CREATE DATABASE test
DEFAULT CHARSET utf8
COLLATE UTF8_GENERAL_Ci;

连接数据库

from peewee import MySQLDatabase, Model, CharField

db = MySQLDatabase(
    host='127.0.0.1',
    user='root',
    passwd='root',
    database='test',
    port=3306
)
db.connect()

数据操作

  • 建立表
class Student(Model):
    stu_num = CharField()
    name = CharField()
    stu_class = CharField()

    class Meta:
        database = db

db.create_table(Student)

# 也可同时建立多个表
db.create_tables([table1, table2, ...])
  • 保存数据
# 第一种
stu = Student(stu_num='test', name='kirito', stu_class='三年二班')
stu.save()
# 第二种
Student.create(stu_num='test', name='kirito', stu_class='三年二班')
  • 读取数据
读取所有数据
for stu in Student.select():
    print('{}\n{}\n{}\n'.format(
        stu.stu_num, stu.name, stu.stu_class))
筛选数据
stu = Student.select().where(Student.name == 'kirito').get()
print(stu.name)

更新数据
stu.name == 'leo'
stu.save()

删除数据
 herb_mittens.delete_instance() 
  • 外键查询
建立一个和student关联的表
class Book(Model):
    book_name = CharField(max_length=50)
    belong_to = ForeignKeyField(Student, related_name='books')

    class Meta:
        database = db

通过student查询属于他的所有book, 这里有两种方法,第二种要好

两次for循环
for stu in Student.select():
    for book in stu.books:
        print(book.book_name)
一次for循环
query = (Book.select(Book, Student).join(Student))
for book in query:
    print(book.book_name)

相关文章

  • Peewee 上手

    peewee是python编写的ORM,ORM是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转...

  • Peewee 使用

    Peewee系列:Peewee 使用Peewee使用之事务Peewee批量插入数据Peewee 使用(二)——增删...

  • Peewee使用之事务

    Peewee系列:Peewee 使用Peewee使用之事务Peewee批量插入数据Peewee 使用(二)——增删...

  • Peewee批量插入数据

    Peewee系列:Peewee 使用Peewee使用之事务Peewee批量插入数据Peewee 使用(二)——增删...

  • 轻量级ORM工具peewee初探

    peewee是什么 peewee是Python一个ORM框架,相比于著名的SQLAlchemy,peewee更为轻...

  • Peewee中文文档

    Peewee中文文档【一】:安装与测试 Peewee中文文档【二】:快速开始 Peewee中文文档【三】:应用实例...

  • python 操作 mysql

    python 操作 mysql python ORM peewee 安装:pip install peewee p...

  • SQLAlchemy选型实战

    peewee 与sqlalchemy选型对比 peewee 在github5000星sqlalchemy在gith...

  • python orm框架peewee

    1.准备 官方链接http://docs.peewee-orm.com/en/latest/peewee/api....

  • peewee的一个坑

    peewee是一个轻量级的DB peewee非常适合一般的处理,一般的存储和查询工作都能做到。今天遇到peewee...

网友评论

    本文标题:Peewee 上手

    本文链接:https://www.haomeiwen.com/subject/fhmiottx.html