peewee:一款轻量级的ORM框架
使用ORM有很多好处,其中之一是:隔离数据库与数据库版本之间的差异
sqlalchemy相对完善
peewee相对轻量级,文档质量高。
官方文档:http://docs.peewee-orm.com/en/latest/
1.如何定义表和生成表:
from peewee import *
db = MySQLDatabase('test',host='127.0.0.1',port=3306,user='root',password='root')
class Person(Model):
name = CharField(max_length=20)
birthday = DateField()
class Meta:
database = db # This model uses the "people.db" database.
if __name__ == '__main__':
db.create_tables([Person])
(官方文档)Field与数据库类型的对应关系

2.通过peewee对数据进行增、删、改、查
# 增
uncle_bob = Person(name='bob', birthday=date(1960, 2, 15))
uncle_bob.save()
# 查
# get方法只获取一条数据,在取不到数据时会抛出异常,取出来的是Person类型
Bob = Person.select().where(Person.name == 'Bob').get() #方式1
egg = Person.get(Person.name == 'egg') #方式2
print(egg.birthday)
----------------------------------------------------------------------
# 批量查询,取不到数据不会抛异常
for person in Person.select(): # 支持切片Person.select()[:3]
print(person.name,person.birthday)
# 改
person.birthday = date(1989,11,30)
person.save() # save()可以新建,也可以更新
# 删
person.delete_instance()
本文由mdnice多平台发布