以下是使用Peewee和MySQL随机查询一条数据的示例代码:
import random
from peewee import *
from playhouse.db_url import connect
# 连接MySQL数据库
db = connect('mysql://username:password@host/database')
# 定义模型类
class Person(Model):
name = CharField()
age = IntegerField()
class Meta:
database = db
# 随机查询一条数据
count = Person.select().count()
offset = random.randint(0, count - 1)
person = Person.select().offset(offset).get()
# 输出查询结果
print(f"Name: {person.name}, Age: {person.age}")
其中,connect() 方法用于连接MySQL数据库。在定义模型类时指定 database 属性为 db,表示使用上面建立的数据库连接。
随机查询一条数据的方法如下:
- 使用
count()方法获取表中总记录数。 - 生成一个随机数作为偏移量。
- 使用
offset()方法设置偏移量。 - 使用
get()方法获取一条数据。
最后输出查询结果。




