Python SQLAlchemy practical tips: from novice to expert

王林
Release: 2024-02-25 08:00:57
forward
777 people have browsed it

Python SQLAlchemy 实战秘籍:从新手到专家

sqlAlchemy Introduction

SQLAlchemy is an open sourceObject Relational Mapping (ORM) tool in python that can help you easily Python objects are mapped to tables in database, and database is operated through simple Python code. SQLAlchemy supports a variety of databases, including Mysql, postgresql, SQLite, etc.

SQLAlchemy basic usage

1. Install SQLAlchemy

First, you need to install SQLAlchemy in your Python environment. You can install it using the following command:

pip install sqlalchemy
Copy after login

2. Create database engine

Before using SQLAlchemy, you need to create a database engine. The database engine is the interface that SQLAlchemy uses to communicate with the database. You can use the following code to create a database engine:

from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://user:passWord@host:port/database")
Copy after login

Among them, mysql pymysql is the type of database, user, password, host, port and database are the user name, password, host, port number and database name of the database respectively.

3. Create session

Session is the object used by SQLAlchemy to interact with the database. You can use the following code to create a session:

Session = sessionmaker(bind=engine)
session = Session()
Copy after login

4. Operation database

You can use sessions to perform various operations on the database, such as query, insert, update, and delete. The following are some commonly used operations:

4.1 Query data

You can use the following code to query data:

results = session.query(User).filter(User.name == "John").all()
Copy after login

Among them, User is the table you want to query, the filter() method is used to filter the query results, and the all() method is used to get all queries result.

4.2 Insert data

You can use the following code to insert data:

new_user = User(name="John", age=30)
session.add(new_user)
session.commit()
Copy after login

Among them, User is the table into which you want to insert data, new_user is the new data you want to insert, and the add() method is used to add new data Added to the session, the commit() method is used to commit all modifications in the session.

4.3 Update data

You can use the following code to update data:

user = session.query(User).filter(User.name == "John").first()
user.age = 31
session.commit()
Copy after login

Among them, User is the table in which you want to update data, the filter() method is used to filter the query results, and the first() method is used to obtain the first A query result, age is the field you want to update, and the commit() method is used to commit all modifications in the session.

4.4 Delete data

You can use the following code to delete data:

user = session.query(User).filter(User.name == "John").first()
session.delete(user)
session.commit()
Copy after login

Among them, User is the table from which you want to delete data, the filter() method is used to filter the query results, and the first() method is used to obtain the first A query result, the delete() method is used to delete data, and the commit() method is used to commit all modifications in the session.

SQLAlchemy Advanced Use

1. Relationship mapping

SQLAlchemy helps you easily map Python objects to tables in your database. You can use the following code to define a relationship map:

class User(Base):
__tablename__ = "user"

id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True)
age = Column(Integer)

class Address(Base):
__tablename__ = "address"

id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey("user.id"))
address = Column(String(100))

# 创建关系映射
User.addresses = relationship("Address", back_populates="user")
Address.user = relationship("User", back_populates="addresses")
Copy after login

Among them, User and Address are the two tables you want to map, the __tablename__ attribute specifies the name of the table, id The name, age, and address properties specify the fields of the table. ForeignKey() The function is used to specify foreign key relationships. relationship() Function is used to define relationship mapping.

2. QueryOptimization

SQLAlchemy provides a variety of query optimization techniques that can help you improve query performance. The following are some commonly used query optimization techniques:

2.1 Batch query

You can use batch queries to improve query performance. Batch query can query multiple data rows at one time. You can use the following code to perform batch queries:

users = session.query(User).filter(User.age > 18).all()
Copy after login

Among them, User is the table you want to query, the filter() method is used to filter the query results, and the all() method is used to get all queries result.

2.2 Using Index

You can use indexes to improve query performance. Indexes help the database quickly find the data you want to query. You can use the following code to create an index:

session.execute("CREATE INDEX idx_user_age ON user (age)")
Copy after login

Among them, user is the table you want to create an index on, and age is the field you want to create an index on.

3. TransactionManagement

SQLAlchemy supports transaction management. Transactions help you ensure that database operations either all succeed or all fail. You can use the following code to start a transaction:

session.begin()
Copy after login

You can use the following code to commit a transaction:

session.commit()
Copy after login

您可以使用以下代码来回滚一个事务:

session.rollback()
Copy after login

结语

SQLAlchemy 是一个功能强大且易于使用的 ORM 工具。它可以帮助您轻松地将 Python 对象与数据库中的表进行映射,并通过简单的 Python 代码来对数据库进行操作。本文介绍了 SQLAlchemy 的基本使用和进阶使用。希望您能通过本文学习到 SQLAlchemy 的使用技巧,并将其应用到您的实际项目中。

The above is the detailed content of Python SQLAlchemy practical tips: from novice to expert. For more information, please follow other related articles on the PHP Chinese website!

source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template