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()
详细用法请参见官方文档