python使用peewee(ORM)操作mysql数据库

  • 2025-03-22 20:36:02
  • 开发
  • 59
  • shevechco

之前我们直接学了了flask中使用peewee的方法,这里再重新学习记录下peewee操作mysql的增删改查。

也可以直接查看这里的中文文档https://www.osgeo.cn/peewee/peewee/querying.html

首先我们先要进行peewee的安装,由于我们是连接操作mysql所以还要安装pymysql模块

pip install peewee pymysql

连接数据库配置如下:

from peewee import *
import datetime

#数据库基础配置 db = MySQLDatabase(app.config["DB_NAME"], user=app.config["DB_USER"], password=app.config["DB_PASS"], host=app.config["DB_HOST"], port=app.config["DB_PORT"])
class BaseModel(Model): class Meta: database = db #创建数据表对象 class BPost(BaseModel): id = AutoField() cate_id = SmallIntegerField(6) author_id = IntegerField(11) tag = CharField(max_length=255) alias = CharField(max_length=255) is_top = SmallIntegerField(1) title = CharField(max_length=255) content = TextField() view_num = IntegerField(11) post_time = DateTimeField(formats='%Y-%m-%d %H:%M:%S', default=datetime.datetime.now) update_time = DateTimeField()

#打开数据库
db.connect()
#创建数据表,数据库还得需要提前手工创建,多个表可以直接加到下面列表中
db.create_tables([BPost])

以上配置好以后就可以进行数据的操作,在每个需要操作数据的py文件导入表对象,创建数据库连接以后就可以直接操作表对象了。

1.增加数据,可以使用create方法,也可以使用save,我们先来看create方法

        BPost.create(name=app.config["BLOG_USER_NAME"], 
                     account=app.config["BLOG_USER_ACCOUNT"], 
                     passwd=app.config["BLOG_USER_PASSWD"], 
                     email=app.config["BLOG_USER_EMAIL"], 
                     level=app.config["BLOG_USER_LEVEL"], 
                     status=app.config["BLOG_USER_STATUS"])

是直接通过传入数据即可,接下来看看save方法

                    post = BPost(title=data.get("title"),
                                cate_id=data.get("cate_id"),
                                author_id=current_user.id,
                                is_top=current_app.config["CHECKBOX"][is_top],
                                is_show=current_app.config["CHECKBOX"][is_show],
                                alias=data.get("alias"),
                                tag=data.get("tag"),
                                content=data.get("content"),
                                #content=escape(data.get("content")),
                                view_num=0,
                                post_time=data.get("post_time"))
                    post.save()

save方法是直接实例化表对象时传入数据,然后调用save方法进行保存

2.修改数据,修改数据也可以使用save方法

                post = BPost.get(BPost.id == int(data.get("id")))
                post.title = data.get("title")
                post.cate_id = int(data.get("cate_id"))
                post.is_top = current_app.config["CHECKBOX"][is_top]
                post.is_show = current_app.config["CHECKBOX"][is_show]
                post.alias = data.get("alias")
                post.tag = data.get("tag")
                post.content = data.get("content")
                post.update_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
                post.save()

主要时先查询获取对象,然后使用数据复制到查询到的对象上,然后调用save方法进行保存更新,实际也可以使用update方法进行更新,如下:

BPost.update(view_num=BPost.view_num+1).where(BPost.id == id).execute()
#如果使用save方法就得先查询复制到对象的属性上,再save,如下
post = BPost.get_by_id(id) post.view_num = post.view_num+1 post.save()

如果有更新多个字段,使用逗号隔开即可。

3.删除数据,这里暂列两种删除方式

#第一种
BPost.delete().where(table_obj.id == id).execute()
#第二种
post = BPost.get(User.id == 1)
post.delete_instance()

4.查询数据,如果查询主键可以有多种查询方式

#普通常用的查询
BPost.get(BPost.id == id))
#其他方式
BPost.get_by_id(id)
#或者
BPost[id]

以上是增删改查,还有一些查询条件,如下

BPost.select().where((BPost.cate_id == id) & (BPost.is_show == 1)).order_by(BPost.id.desc())

多个查询条件可以使用&或者|,或者“and”或者“or”,模糊匹配使用contains,如下:

BPost.select().where((BPost.tag.contains(tag)) & (BPost.is_show == 1)).order_by(BPost.id.desc())

排序使用order方法,其中正序和倒序分别是asc()和desc()

分页使用paginate方法,如下

BPost.select().where((BPost.cate_id == id) & (BPost.is_show == 1)).order_by(BPost.id.desc()).paginate(page_num, page_size)

page_num是页数,page_size是每页查询的数量,如果不分页直接查询10条,下面列子带的有。

咱们可能用到的循环拼接like的模糊匹配查询如下

from functools import reduce
import operator

condition = [BPost.tag.contains(tag) for tag in post.tag.split(",")]
condition1 = reduce(operator.or_, condition )
BPost.select().where(condition1 & (BPost.is_show == 1) & (BPost.id != id)).order_by(BPost.id.desc()).limit(10)

最后使用完以后记得关闭数据库连接

database.close()

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.sulao.cn/post/1002

相关推荐