数据库的model.py
时间: 2024-05-14 09:18:22 浏览: 15
数据库的 `model.py` 文件是用来定义数据模型的,通常使用 ORM(Object-Relational Mapping)框架来实现。ORM是一种将关系数据库中的表映射到对象的技术,因此在代码中可以像操作对象一样操作数据库,而不必直接使用 SQL 语句。
在 `model.py` 中,我们需要定义每个表对应的类,每个类对应一个数据表,类中的属性对应表中的字段。例如,下面是一个简单的示例:
```python
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
```
在这个示例中,我们定义了一个名为`User`的类,它继承了`declarative_base()`返回的基类`Base`。`__tablename__`属性指定了这个类对应的数据表名为`users`。类中还定义了三个属性,分别对应表中的`id`、`name`和`email`字段。
通过这样的方式,我们就可以通过 ORM 框架来操作数据库,例如:
```python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///example.db')
Session = sessionmaker(bind=engine)
session = Session()
user = User(name='Alice', email='alice@example.com')
session.add(user)
session.commit()
users = session.query(User).all()
for user in users:
print(user.name, user.email)
```
这段代码使用了 SQLAlchemy 来连接 SQLite 数据库,创建了一个`User`对象并将其添加到数据库中,然后查询了所有的用户并打印它们的名字和邮箱。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)