Home > Article > Backend Development > How to use SQLAlchemy for database operations
How to use SQLAlchemy for database operations
SQLAlchemy is a popular Python library used to simplify interaction and operation with relational databases. It provides an object-relational mapping (ORM) approach that allows developers to use Python code to operate the database without writing original SQL statements. This article will introduce how to use SQLAlchemy for database operations, and attach code examples to help readers get started quickly.
First, you need to install the SQLAlchemy library. Execute the following command in the command line to complete the installation:
pip install sqlalchemy
Before starting, you need to connect to the target database. SQLAlchemy supports a variety of databases, including MySQL, PostgreSQL, SQLite and Oracle. The following code example connects to a SQLite database:
from sqlalchemy import create_engine # 创建数据库引擎 engine = create_engine('sqlite:///example.db')
The above code creates a SQLite database engine and specifies the path to the database file. If you need to connect to other types of databases, just replace "sqlite" in the connection string with the corresponding database type.
The core concept of using SQLAlchemy for ORM operations is the data model. The data model is represented by Python classes, each class corresponding to a table in the database. The following code example defines a data model named "User":
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)
The above code defines a data model named "User" and the table name is "users". Each attribute in the data model corresponds to a column in the table, where "id" is the primary key column.
Before using the data model, you need to create the corresponding table. The following code example creates a table named "users":
Base.metadata.create_all(engine)
The above code uses the definitions in the data model to automatically create the corresponding table structure.
Once the table structure is created, you can start database operations. The following code example inserts a new user record:
from sqlalchemy.orm import sessionmaker # 创建会话工厂 Session = sessionmaker(bind=engine) session = Session() # 创建新用户 new_user = User(name='John Doe', email='johndoe@example.com') # 添加到会话 session.add(new_user) # 提交事务 session.commit()
The above code uses the session object for database operations. First a session factory is created and bound to the database engine. Then create a session object through the session factory. Then a new user object is created and added to the session using the session.add()
method. Finally, use session.commit()
to commit the transaction and save the data to the database.
When using SQLAlchemy for query operations, you can use query expressions or SQL statements. The following code example queries all user records:
# 查询所有用户 users = session.query(User).all() # 打印查询结果 for user in users: print(user.name, user.email)
The above code uses session.query(User)
to create a query object, and then calls the .all()
method to execute Query operation returns all user records. You can obtain the attribute value of each record by traversing the query results.
Updating data can be done in several different ways. The following code example updates the email address of the specified user:
# 查询指定用户 user = session.query(User).filter_by(name='John Doe').first() # 更新电子邮件地址 user.email = 'newemail@example.com' # 提交事务 session.commit()
The above code uses session.query(User).filter_by(name='John Doe').first()
to query the specified User records and updates data by modifying their attribute values.
Deleting data can also be done in a few different ways. The following code example deletes the specified user:
# 查询指定用户 user = session.query(User).filter_by(name='John Doe').first() # 删除用户 session.delete(user) # 提交事务 session.commit()
The above code uses session.delete(user)
to delete the specified user record.
The above introduces the basic steps of how to use SQLAlchemy for database operations, and gives corresponding code examples. SQLAlchemy is very rich in functions, including transaction management, advanced query and other functions. Readers can further study and explore it. I hope this article can help readers quickly get started with SQLAlchemy and improve the efficiency and convenience of database operations.
The above is the detailed content of How to use SQLAlchemy for database operations. For more information, please follow other related articles on the PHP Chinese website!