定义 Model
在使用的时候,根据需求先定义好Model,然后可以通过create_tables()创建表,若是已经创建好数据库表了,可以通过python -m pwiz脚本工具直接创建Model
新的数据表
先定义Model,然后通过db.create_tables()创建或Model.create_table()创建表。
例如,我们需要建一个Person表,里面有name、birthday和is_relative三个字段,我们定义的Model如下:
from peewee import *
# 连接数据库
database = MySQLDatabase('test', user='root', host='localhost', port=3306)
# 定义Person
class Person(Model):
name = CharField()
birthday = DateField()
is_relative = BooleanField()
class Meta:
database = database
然后,我们就可以创建表了
# 创建表
Person.create_table()
# 创建表也可以这样, 可以创建多个
# database.create_tables([Person])
其中,CharField、DateField、BooleanField等这些类型与数据库中的数据类型一一对应,我们直接使用它就行,至于CharField => varchar(255)这种转换Peewee已经为我们做好了
已存在的数据表
已经存在过数据库,则直接通过python -m pwiz批量创建Model。
例如,上面我已经创建好了test库,并且创建了Person表,表中拥有id、name、birthday和is_relative字段。那么,我可以使用下面命令:
# 指定mysql,用户为root,host为localhost,数据库为test
python -m pwiz -e mysql -H localhost -p 3306 -u root -P root -t elephdev_table elephdev_db > dbmodel/elephdev_table.py
操作数据库
insert
直接创建示例,然后使用save()就添加了一条新数据
# 添加一条数据
p = Person(name='liuchungui', birthday=date(1990, 12, 20), is_relative=True)
p.save()
delete
使用delete().where().execute()进行删除,where()是条件,execute()负责执行语句。若是已经查询出来的实例,则直接使用delete_instance()删除
# 删除姓名为perter的数据
Person.delete().where(Person.name == 'perter').execute()
# 已经实例化的数据, 使用delete_instance
p = Person(name='liuchungui', birthday=date(1990, 12, 20), is_relative=False)
p.id = 1
p.save()
p.delete_instance()
update
若是,已经添加过数据的的实例或查询到的数据实例,且表拥有primary key时,此时使用save()就是修改数据;若是未拥有实例,则使用update().where()进行更新数据
# 已经实例化的数据,指定了id这个primary key,则此时保存就是更新数据
p = Person(name='liuchungui', birthday=date(1990, 12, 20), is_relative=False)
p.id = 1
p.save()
# 更新birthday数据
q = Person.update({Person.birthday: date(1983, 12, 21)}).where(Person.name == 'liuchungui')
q.execute()
select
单条数据使用Person.get()就行了,也可以使用Person.select().where().get()。若是查询多条数据,则使用Person.select().where(),去掉get()就行了。语法很直观,select()就是查询,where是条件,get是获取第一条数据
# 查询单条数据
p = Person.get(Person.name == 'liuchungui')
print(p.name, p.birthday, p.is_relative)
# 使用where().get()查询
p = Person.select().where(Person.name == 'liuchungui').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)
发表评论 取消回复