一、建立连接
hot_host = "127.0.0.1"
hot_port = 3306
hot_db = "KTS"
hot_user = "root"
hot_pass = "pass123"
db = MySQLDatabase(host=hot_host, port=hot_port, user=hot_user, passwd=hot_pass, database=hot_db)
db.connect()
二、定义模型
class BaseModel(Model):
class Meta:
database = db
class Person(BaseModel):
name = CharField()
age = IntegerField()
sex = BooleanField(default="male")
三、迁移表及增删改查
# 迁移生成表 db.create_tables([Person])
Person.create_table()
# 增 插入一条数据
Person.create(name="tonsy", age=31, sex="female")
# 查询
# 单条查询 简写 Model.get() 也可以使用Person.select().where().get()
# 多条查询 使用Person.select().where()
# 查询结果转字典 .dicts() Person.select().where(Person.age==31).dicts()
p = Person.get(Person.age==31)
p = Person.select().where(Person.age==31).dicts()
# 删除数据
Model.delete().where().execute()
Person.delete().where(Person.age==31).execute()
# 改
Model.update().where().excute()
Person.update({"age":21}).where(Person.name=="tom1").execute()
Person.update(age=22).where(Person.name=="tom1").execute()