Python ORM之peewee模块

由于peewee用起来比较简单 ,  所以了解了一下

以Python内置的数据库SQLite为例

python3.7版本

 1 import peewee
 2 conn = peewee.SqliteDatabase('xxx.db') #sqlite中创建并连接数据库
 3 
 4 class Stock(peewee.Model):
 5     symbol = peewee.CharField(unique=True)
 6     exchange = peewee.CharField()
 7     price = peewee.FloatField(default=0.0)
 8     class Meta:
 9         database = conn
10         
11 Stock.create_table() #创建表
12 Stock.delete().where(True).execute() #清空表数据
13 #插入数据
14 Stock.create(symbol='000001',exchange='SH',price=37.5)
15 #插入数据的等价方法1
16 Stock.insert(symbol='000002',exchange='SZ',price=48.2).execute()
17 #插入数据的等价方法2
18 Stock(symbol='000003',exchange='HK').save()
19 
20 def query(symbol):    #自定义一个查询方法
21     stocks = Stock.select().where(Stock.symbol in symbol) #查询之后返回的是包含每行记录(Stock实例对象)的迭代对象
22     for stock in stocks:
23         print("symbol:{}, exchange:{}, price:{}".format(stock.symbol,stock.exchange,stock.price))
24         
25 query(['000001','000002','000003']) #进行查询
26 
27 T = Stock.select().where(Stock.symbol in ['000001','000002']).get() #get方法返回第一条数据记录
28 print("查询单条数据:\nsymbol:{}, exchange:{}, price:{}".format(T.symbol,T.exchange,T.price))
29 
30 Stock.update(price=100.12).where(Stock.symbol=='000001').execute() #更新数据update
31 
32 print('查询更新之后的数据:')
33 query(['000001','000002','000003']) #更新数据之后再次查询
34 
35 # 用原生SQL执行查询
36 print('直接使用SQL语法:')
37 cursor = conn.cursor()
38 cursor.execute('select symbol,exchange,price from Stock group by symbol having price>0 order by price asc')
39 for row in cursor:
40     print(row)

结果如下图

数据库表和Python的类是对应的 , 类需要继承peewee.Model类 , 每次进行增删改查都是对类直接进行操作

增insert 删delete 改update 需要调用execute()方法 select不需要

列名和类(实例)属性对应 

表中的一行记录对应 类的实例对象 查询结果返回的是一个可迭代对象 用for遍历 每次遍历结果都是一个行记录 也是一个类的实例对象 

可以使用原生的SQL语法 , 通过游标直接进行数据库操作 解决复杂查询还是这个比较方便

创建表之后会自动创建一个自增的名为Id的列

谢谢!

posted @ 2019-05-29 16:50  布里塔  阅读(470)  评论(0编辑  收藏  举报