栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 轻量级ORM框架 peewee

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 轻量级ORM框架 peewee

python三大ORM工具: django orm、sqlalchemy、peewee,其中peewee是轻量级的。 1.peewee简介

peewee 是一个轻量级的 python ORM 库,简单灵活,申明方式和django的ORM接近,并且官方文档质量高。内建对 SQLite、MySQL 和 PostgreSQL 的支持。

Github:https://github.com/coleifer/peewee

官方文档:peewee — peewee 3.14.4 documentation

使用ORM的优势:

(1)隔离数据库和数据库版本之间的差异

(2)便于维护

(3)ORM会提供防SQL注入等功能

(4)变量传递式的调用更加简单

2.安装
pip install peewee
3.基本用法

(1)创建表

from peewee import *
db = MySQLDatabase('spider', host='hadoop1', port=3306, user='root', password='123456')
"""
1.如果不设置主键,默认会增加一个字段id作为主键

"""
class Person(Model):
    name = CharField(max_length=200, null=True)
    birthday = DateField()

    class meta:
        database = db # This model uses the "spider" database.
        table_name = 'users' # 如果不指定,默认是person
if __name__ == '__main__':
    # 创建表
    db.create_tables([Person])

生成的表如下所示:

 (2)插入数据

    from datetime import date
    uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15))
    uncle_bob.save()  # bob is now stored in the database

(3)单条查询

说明:查询数据(只获取一条), get方法在取不到数据会抛出异常,要使用try catch进行捕获

方式一: 

    bob = Person.select().where(Person.name == 'Bob').get()
    print(bob.name, bob.birthday)

方式二:

    bob = Person.get(Person.name == 'Bob')
    print(bob.name, bob.birthday)

(4)批量查询

    for person in Person.select():
    print(person.name)



    # query是modelselect对象 可以当做list来操作
    query = Person.select().where(Person.name=='Bob')
    for person in query:
        print(person.name)

(5)修改数据

    query = Person.select().where(Person.name=='Bob')
    for person in query:
        person.birthday = date(2021, 10, 22)
        # 在没有数据的时候新增数据,存在数据的时候修改数据
        person.save()

(6)删除数据

    query = Person.select().where(Person.name == 'Bob')
    for person in query:
        person.delete_instance()

详细用法请参见官方文档

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/341326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号