轻量级ORM库peewee的基本使用

peewee

Peewee是一种简单而小的ORM。它只有很少的(但富有表现力的)概念,使它易于学习和直观的使用。它支持sqlite、mysql、postgresql和cockroachdb

官网文档传送门: peewee
GitHub:peewee

from peewee import *

db = MySQLDatabase('mydb', host="localhost", user='root', passwd='12345', port=3306)


# 定义模型类Person
class Person(Model):
  name = CharField()
  birthday = DateField()
  is_relative = BooleanField()

  class Meta:
    database = db
    
def test_create_table():
  Person.create_table()
  # 还可以这样创建多张表
  # database.create_tables([Person])


def test_insert_data():
  # 在Person表插入一条数据
  p = Person(name='哆啦A梦', birthday=date(2000, 1, 1), is_relative=True)
  p.save()


def test_delete_data():
  # 删除姓名为李云龙的数据
  Person.delete().where(Person.name == '李云龙').execute()
  
  # 已实例化的数据, 使用delete_instance
  p = Person(name='哆啦A梦', birthday=date(2000, 1, 1), is_relative=False)
  p.id = 1
  p.save()
  p.delete_instance()


def test_update_data():
  # 已经实例化的数据,指定了id这个primary key,则此时保存相当于更新数据
  p = Person(name='哆啦A梦', birthday=date(2000, 1, 1), is_relative=False)
  p.id = 1
  p.save()

  # 更新姓名为哆啦A梦的用户的birthday数据
  q = Person.update({Person.birthday: date(1900, 1, 1)}).where(Person.name == '哆啦A梦')
  q.execute()


def test_query_data():
  # 查询单条数据
  p = Person.get(Person.name == '哆啦A梦')
  print(p.name, p.birthday, p.is_relative)

  # 使用where().get()查询
  p = Person.select().where(Person.name == '哆啦A梦').get()
  print(p.name, p.birthday, p.is_relative)

  # 查询多条数据
  persons = Person.select().where(Person.is_relative == True)
  for p in persons:
    print(p.name, p.birthday, p.is_relative)

#创建表,然后插入数据
if __name__=="__main__":
  Person.create_table()
  p = Person(name='哆啦A梦', birthday=date(2000, 1, 1), is_relative=True)
  p.save()

以上即是peewee库常用的增删改查等基础方法

#批量查询
if __name__ == "__main__":
  for i in range(1, 5):
    p = Person(name=f'小张{i}', birthday=date(2008, 8, 8), is_relative=False)
    p.save()
  # 查询多条数据
  persons = Person.select().where(Person.is_relative == False)
  for p in persons:
    print(p.name, p.birthday, p.is_relative)

#测试:更新数据

if __name__ == "__main__":
  p = Person(name='李云龙', birthday=date(2001, 1, 1), is_relative=False)
  p.save()
  # 更新birthday数据
  q = Person.update({Person.birthday: date(2002, 1, 1)}).where(Person.name == '李云龙')
  q.execute()

#测试:删除数据
if __name__=="__main__":
  Person.delete().where(Person.name == '哆啦A梦').execute()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木法星人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值