from peewee import MySQLDatabase, Model
from peewee import CharField, IntegerField, BooleanField
# 引入 随机数据包
import random
from faker import Faker
fake = Faker('zh_CN')
# 创建 mysql 连接关系
mysql_db = MySQLDatabase("peewee", user="root", host="127.0.0.1", port=3306, passwd="123456", charset='utf8')
'''
需要手动添加 mysql 的驱动库,不是光添加一个 MySQLDatabase 就能行的
pip install pymysql
'''
# 创建链接基类
class BaseModel(Model):
class Meta:
database = mysql_db
class User(BaseModel):
username = CharField() # 名字为 varchar 类型
age = IntegerField() # 年龄为 int 类型
is_graduate = BooleanField() # 是否毕业,bool 类型
class Meta:
db_table = "test_user"
def create_date():
users = []
for i in range(20):
age = random.randint(1, 82)
users.append({"username": fake.name(), "age": age, "is_graduate": age > 22})
with mysql_db.atomic():
query = User.insert_many(users)
query.execute()
if __name__ == "__main__":
first = True
if first:
User.create_table() # 创建表
else:
User.drop_table() # 删除表
# create_date()
user_01 = User.select().where(User.id == "1").get()
print(user_01.username)
print(type(user_01))
参考文献
https://geek-docs.com/python/python-tutorial/python-peewee.html#ftoc-heading-9
https://docs.peewee-orm.com/en/latest/peewee/query_operators.html