Peewee 上手

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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转载,觉得这篇写 SQLAlchemy Core,写得非常不错。不过后续他没写SQLAlchemy ORM... ...
    非梦nj阅读 5,499评论 1 14
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,556评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 《王六郎》断背河传说之五里,我否定了蒲松龄和王观正一起游般河,拿了宋琬诗题目做证据。 其实,比较王观正和蒲松龄的诗...
    觉史氏阅读 435评论 1 0
  • 我之所有,我之所能,都归功于我天使般的母亲。——林肯 国庆长假期间,广州南沙区出现了令人感动的一幕。有位老母亲路过...
    悦读时刻阅读 742评论 5 3