[100 days proficient in python] Day34: Use python to operate database_ORM (SQLAlchemy) use

Table of contents

 Column Guide 

1 ORM overview

2 SQLAlchemy overview

3 ORM: using SQLAlchemy

 3.1 Install SQLAlchemy:

3.2 Define the database model class:

3.3 Create a data table:

3.4 Insert data:

 3.5 Query data:

3.6 Update data:

3.7 Delete data:

3.8 Closing the session:

4 combat

  Design a simple library management system.


 Column Guide 

Column subscription address: https://blog.csdn.net/qq_35831906/category_12375510.html


1 ORM overview

        ORM (Object Relational Mapping) is a programming technology used to establish a mapping relationship between a relational database and an object-oriented programming language, so that tables and records in the database can be mapped to objects and classes in the programming language. The goal of an ORM is to simplify database operations, enabling developers to work with databases in an object-oriented manner.

        In Python, there are several ORM libraries available, the most well-known of which is SQLAlchemy. SQLAlchemy provides a way to establish a mapping relationship between Python objects and database tables, allowing developers to use Python classes to operate databases.

Advantages of ORMs include:

  1. Abstract database operations : ORM hides the details of the underlying database, and developers can focus more on business logic without writing complex SQL queries.

  2. Object-oriented programming : ORM allows developers to process data in an object-oriented manner, making the code clearer and more maintainable.

  3. Cross-database support : ORM libraries usually provide support across multiple databases, and developers can easily switch databases without changing a lot of code.

  4. Automatic table creation and migration : The ORM library can automatically generate database tables based on defined Python classes, and supports database migration.

  5. Query Builder : ORM libraries usually provide a query builder that makes writing queries easier and more intuitive.

  6. Transaction management : ORM libraries can help manage transactions to ensure data consistency and integrity.

2 SQLAlchemy overview

        SQLAlchemy is a powerful Python SQL toolkit and object-relational mapping (ORM) library that allows developers to use the Python programming language to interact with relational databases. SQLAlchemy provides a flexible and powerful way to perform operations such as SQL queries, inserts, updates, deletes, etc., and also supports mapping database tables to Python classes, enabling developers to manipulate databases in an object-oriented manner.

Here are the main features and overview of SQLAlchemy:

  1. ORM functionality : One of the core features of SQLAlchemy is its ORM functionality. It allows you to map database tables and records by defining Python classes, transforming database operations into object-oriented operations, making the code more intuitive and easier to maintain.

  2. Multiple database support : SQLAlchemy supports multiple relational databases, including MySQL, SQLite, PostgreSQL, Oracle, etc., allowing developers to switch between different databases without changing most of the code.

  3. Flexibility : SQLAlchemy provides a variety of ways to perform SQL operations, including raw SQL queries, query builders, and ORM queries. This allows developers to choose a suitable method according to their needs.

  4. Connection pool management : SQLAlchemy supports connection pool management, which can maintain a set of database connections between applications and databases to improve performance and efficiency.

  5. Transaction management : SQLAlchemy allows you to use transaction management to ensure the consistency and integrity of database operations, you can commit, rollback and interrupt transactions.

  6. Database migration : SQLAlchemy provides the Alembic tool for database migration and version management, making changes to the database structure more controllable.

  7. Multiple associations : SQLAlchemy supports multiple association types, such as one-to-many, many-to-many and other associations, making the relationship between databases clearer.

  8. Cross-table query : SQLAlchemy allows performing cross-table joins in ORM queries, enabling complex query operations.

  9. Performance optimization : SQLAlchemy provides various performance optimization options, such as caching, batch operations, etc., to improve the efficiency of large-scale data processing.

  10. Rich documentation and community support : SQLAlchemy has rich official documentation and an active community, making it easier to learn and solve problems.

        In conclusion, SQLAlchemy is a powerful Python database toolkit suitable for projects of all sizes, from small applications to large enterprise-level systems. Its flexibility, object-oriented design, and multiple functions make it one of the preferred tools for Python developers to perform database operations.

3 ORM: using SQLAlchemy

        When using an ORM in Python (such as SQLAlchemy), you define your database models by creating Python classes, and then use those model objects to perform database operations. Here is a detailed example using SQLAlchemy:

3.1  Install SQLAlchemy :

First, you need to install the SQLAlchemy library. You can install it in terminal with the following command:

pip install sqlalchemy

3.2 Define the database model class :

Create a Python class to define the database model. Each class represents a table, and the attributes of the class represent the columns of the table.

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

# 创建数据库连接
engine = create_engine('sqlite:///example.db')
Base = declarative_base()

# 定义模型类
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

3.3 Create a data table :

Create a database table by calling create_all()a method.

Base.metadata.create_all(engine)

3.4 Insert data :

Create a model object, then add it to the session and commit.

from sqlalchemy.orm import sessionmaker

# 创建会话
Session = sessionmaker(bind=engine)
session = Session()

# 添加数据
new_user = User(name='Alice', age=25)
session.add(new_user)
session.commit()

 3.5  Query data :

Use sessions to query model objects.

# 查询数据
user = session.query(User).filter_by(name='Alice').first()
if user:
    print("User found:", user.name, user.age)
else:
    print("User not found")

3.6 Update data :

Properties of model objects can be updated and then the session submitted to update the database.

user.age = 26
session.commit()

3.7 Delete data :

Use delete()the method to delete the model object and then submit the session.

session.delete(user)
session.commit()

3.8   Closing the session :

Remember to close the session when you're done.

session.close()

4 combat

  Design a simple library management system.

Here is a complete example of a library management system using SQLAlchemy: 

Make sure sqlalchemy is installed, pip install sqlalchemy

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 创建数据库连接
engine = create_engine('sqlite:///library.db')
Base = declarative_base()

# 定义作者模型类
class Author(Base):
    __tablename__ = 'authors'
    id = Column(Integer, primary_key=True)
    name = Column(String)

# 定义图书模型类
class Book(Base):
    __tablename__ = 'books'
    id = Column(Integer, primary_key=True)
    title = Column(String)
    author_id = Column(Integer, ForeignKey('authors.id'))

# 创建数据表
Base.metadata.create_all(engine)

# 创建会话
Session = sessionmaker(bind=engine)
session = Session()

# 添加作者
author1 = Author(name='J.K. Rowling')
author2 = Author(name='George Orwell')

session.add_all([author1, author2])
session.commit()

# 添加图书
book1 = Book(title='Harry Potter and the Sorcerer\'s Stone', author_id=author1.id)
book2 = Book(title='1984', author_id=author2.id)

session.add_all([book1, book2])
session.commit()

# 查询数据
print("Authors:")
authors = session.query(Author).all()
for author in authors:
    print("Author:", author.name)

selected_author = session.query(Author).filter_by(name='J.K. Rowling').first()
if selected_author:
    print("\nBooks by", selected_author.name)
    books = session.query(Book).filter_by(author_id=selected_author.id).all()
    for book in books:
        print("Book:", book.title)

# 关闭会话
session.close()

The above code sample demonstrates how to create a simple book management system using the SQLAlchemy library.

  1. Import required modules : The required SQLAlchemy modules are imported at the beginning of the code, including creating engines, defining model classes, creating data tables and sessions, etc.

  2. Creating a database connection and base class : create_engineCreated a SQLite database connection using a function, and then declarative_basecreated a base class via Base.

  3. Define model classes : Two model classes are defined, namely Author(Author) and Book(Book). Each class corresponds to a table, and the attributes of the class correspond to the columns of the table.

  4. Create a data table : By calling Base.metadata.create_all(engine)a method, a data table in the database is created based on the model class.

  5. Create a session : use to sessionmakercreate a session class Session, and then Session()create a session instance session.

  6. Adding data : Created two author instances, session.add_all()added them to the session using , and session.commit()committed to the database via .

  7. Query data : session.query()The author and book information were queried and printed out.

  8. Closing the session : After all operations are completed, session.close()resources are released by closing the session.

Overall, this example shows how to use SQLAlchemy to create database models, perform database operations, query data, and close sessions. By using ORM, you can convert database operations into an object-oriented way, making the code clearer and more maintainable. You can extend this example further, adding more functionality and complexity as needed.

 

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/132271771