Contents
为啥使用 ORM
- 隔离数据库 和 数据库版本之间的差异
- 便于维护
- ORM 会提供防 sql 注入功能
- 变量传递式的调用更加简单
- 很多励志不用 orm 的项目会慢慢的开发自己的一套 orm
为什么选择 peewee
- django orm ,sqlalchemy,peewee
- 简单 灵活 申明方式和djano orm 接近
- star 数量高 活跃度高
- 文档质量高
peewee 生成表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from peewee import * db = MySQLDatabase("peewee",host="localhost",port=3306,user="root",password="root") class Person(Model): name = CharField(max_length=20,null=True) birthday = DateTimeField() class Meta: database = db table_name = "user" if __name__ == '__main__': db.create_tables([Person]) |
peewee 增删改查
peewee 新增数据
1 2 3 4 5 |
# 增加数据 from datetime import date songhao = Person(name='songhao',birthday = date(2000,1,10)) songhao.save() |
peewee 查询
只能返回一条数据
1 2 3 4 |
# 查询数据 songhao = Person.select().where(Person.name == 'songhao').get() songhao 是对象而不是数字 |

Model 通过 get 方法获取更为合适
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
>>> User.get(User.id == 1) <__main__.User object at 0x25294d0> >>> User.get_by_id(1) # Same as above. <__main__.User object at 0x252df10> >>> User[1] # Also same as above. <__main__.User object at 0x252dd10> >>> User.get(User.id == 1).username u'Charlie' >>> User.get(User.username == 'Charlie') <__main__.User object at 0x2529410> >>> User.get(User.username == 'nobody') UserDoesNotExist: instance matching query does not exist: SQL: SELECT t1."id", t1."username" FROM "user" AS t1 WHERE t1."username" = ? PARAMS: ['nobody'] |
获取多条数据 Model.select()
1 2 3 4 5 6 7 8 9 |
# cmd 中查询 datas = Person.select() [p.name for p in datas] Out[3]: ['songhao', 'songhao808', 'songhao8080'] datas[0] Out[4]: <Person: 1> datas[0].name Out[5]: 'songhao' |

修改数据
1 2 3 4 5 |
<br />for p in datas: p.name = "hello world" p.save() |

删除数据
1 2 3 4 5 |
# 删除操作 for p in datas: p.delete_instance() |

