常见 python orm 有:
pip install pymysql
pip install peewee
module.py
from peewee import MySQLDatabase
database = 'test'
host='127.0.0.1'
user='root'
passwd=''
port=3306
db = MySQLDatabase(database, host, user, passwd, port, charset='utf8mb4')
# 查询数据库是连接
print(db.is_closed()) # 返回false未连接
# 连接数据库
db.connect()
module.py
from datetime import datetime
from peewee import MySQLDatabase, Model, CharField, DateTimeField, IntegerField, FixedCharField
class BaseModel(Model):
class Meta:
# 将实体与数据库进行绑定
database = db
# 继承自BaseModel,直接关联db,并且也继承了Model。Model有提供增删查改的函数
class CheckLog(BaseModel):
# IntegerField->int
uid = IntegerField(verbose_name='用户编号')
action = CharField(verbose_name='行为', max_length=30)
# DateTimeField->datetime
time = DateTimeField(default=datetime.now())
class Users(BaseModel):
# CharField->varchar null->非空约束
name = CharField(verbose_name='姓名', max_length=10, null=False)
passwd = CharField(verbose_name='密码', max_length=20, null=False)
phone = FixedCharField(verbose_name='手机号')
if __name__ == '__main__':
# 创建表
Users.create_table()
CheckLog.create_table()
sqltest.py
from models.model import Users, CheckLog
def insert_models():
users = Users()
users.name = "admin"
users.passwd = "admin123"
users.phone = "13996693254"
users.save() # 一定要 save
check_log = CheckLog()
check_log.uid = users.id
check_log.action = f"创建用户{users.name}"
check_log.save() # 一定要 save
if __name__ == '__main__':
insert_models()
sqltest.py
def query_models():
# 获取某一条数据
print(Users.get(Users.id == 1).name)
# 或
print(Users.get_by_id(1).name)
# 或
print(Users[1].name) # 这里的 1 是 id
# 获取全部数据
users = Users.select()
for user in users:
print(user.name)
if __name__ == '__main__':
query_models()
sqltest.py
def update_models():
user = Users.get_by_id(1)
user.name = "test"
user.save()
check_log = CheckLog()
check_log.uid = user.id
check_log.action = f"修改用户名{user.name}"
check_log.save()
# 或
Users.update(name="test").where(Users.id == 1).execute()
if __name__ == '__main__':
update_models()
sqltest.py
def del_models():
# user = Users.get_by_id(1)
# user.delete_instance()
# 或
Users.delete().where(Users.id == 1).execute()
if __name__ == '__main__':
del_models()