利用peewee读取db数据库并查询指定数据
时间: 2024-06-09 14:09:30 浏览: 5
好的,您可以使用以下代码利用 peewee 读取 db 数据库并查询指定数据:
```python
import peewee
db = peewee.SqliteDatabase('database.db')
class User(peewee.Model):
name = peewee.CharField()
age = peewee.IntegerField()
class Meta:
database = db
# 查询指定数据(例如名字为 John 的用户)
query = User.select().where(User.name == 'John')
# 遍历查询结果并输出对应信息
for user in query:
print(user.name, user.age)
```
这段代码会从名为 `database.db` 的数据库文件中读取数据,并且查询符合条件(名字为 John)的用户信息,并逐行输出对应的名字和年龄。请确保您已经安装了 peewee 库,并且将代码中的数据库文件名和表格字段按照实际情况进行修改。
相关问题
利用peewee读取db数据库
好的,您可以使用以下代码利用 peewee 读取 db 数据库:
```python
from peewee import *
# 创建数据库连接
db = SqliteDatabase('my_database.db')
# 创建模型类
class User(Model):
username = CharField()
email = CharField()
class Meta:
database = db
# 查询数据
users = User.select()
for user in users:
print(user.username, user.email)
```
其中,'my_database.db' 是您的数据库文件路径,User 是模型类,它可以映射到您的数据库表。在上述示例中,我们执行了一个查询,返回了所有的 User 记录,并打印了每个记录的 username 和 email 字段。
请注意,您需要确保在代码中正确配置数据库连接和模型类,方能顺利地读取数据库。
peewee创建sqlite数据库并添加数据
好的,关于你的问题,下面是使用 peewee 创建 SQLite 数据库并添加数据的示例代码:
```
import peewee
# 创建 SQLite 数据库连接
db = peewee.SqliteDatabase('mydatabase.db')
class Person(peewee.Model):
name = peewee.CharField()
age = peewee.IntegerField()
class Meta:
database = db
# 创建表格
Person.create_table()
# 添加数据
person = Person(name='John', age=25)
person.save()
```
这个示例代码中,我们首先使用 peewee 创建 SQLite 数据库连接,并定义了一个 Person 模型(包括了 name 和 age 两个字段),然后创建表格并添加了一条数据。
希望这个回答能够解决你的问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)