What is the usage of the ORM framework in Python?
In Python, the ORM (Object Relational Mapping) framework is used to map data from a database to Python objects, allowing programmers to manipulate the database in an object-oriented manner without having to directly write SQL statements.
Common Python ORM frameworks include SQLAlchemy, Django ORM, and Peewee.
The general steps of using an ORM framework are as follows:
- Defining model classes: Mapping tables in the database as a class using Python classes, where the class attributes correspond to the table fields, and the class methods correspond to table operations (insert, update, delete, retrieve).
- Establishing a database connection: Utilize the API provided by the ORM framework to establish a connection with the database.
- Create table structure: Use the methods provided by the ORM framework to generate the corresponding table structure based on the model class.
- CRUD operations: performing database operations such as adding, deleting, modifying, and querying by calling methods of the model class. For example, creating an object and saving it to the database, updating object properties and saving them, and querying the database based on certain conditions.
- Close the database connection: Disconnect from the database when the program ends.
Here is an example using SQLAlchemy as an ORM framework:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# 创建引擎
engine = create_engine('数据库连接字符串')
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# 创建基类
Base = declarative_base()
# 定义模型类
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# 创建表结构
Base.metadata.create_all(engine)
# 增删改查操作
user = User(name='Alice', age=20)
session.add(user)
session.commit()
user.age = 22
session.commit()
users = session.query(User).filter(User.age > 18).all()
for user in users:
print(user.name, user.age)
# 关闭会话
session.close()
In the above example, the database engine and session are first created, a model class User is defined, then table structure is created based on the model class, followed by CRUD operations. Finally, the session is closed.