Python's ORM - SQLAlchemy use

ORM

Let's first understand what is ORM, and what problems does ORM use to solve?

In the process of developing web applications, we will inevitably involve CRUD operations, so we need to use database management software, such as mysql, oracle, Microsoft SQL Server, etc.

If the application needs to operate data (such as permanently storing user registration information), then we need to write native SQL statements in the application, and then use the pymysql module to remotely operate the mysql database

However, there are two problems in directly writing native SQL statements, which seriously affect the development efficiency, as follows

  1. Execution efficiency of sql statements: application development programmers need to spend a lot of energy to optimize sql statements
  2. Database migration problem: the sql statement developed for mysql cannot be directly applied to the oracle database. Once the database needs to be migrated, cross-platform issues need to be considered
  3. When writing business logic code, it takes a lot of energy to write complicated codes to implement database addition, deletion, modification and query, which makes the data access layer too large

In order to solve the above problems, the concept of ORM is introduced. The full name of ORM is Object Relational Mapping, that is, Object Relational Mapping. It mainly describes the mapping relationship between the Object object in the program and the Rlation relationship (table) in the relational database. It is a A programming idea for data persistence between programs and databases. It is a layer of encapsulation on top of pymysq. For data operations, we no longer need to write native SQL. Instead, we write classes, objects, and call corresponding methods based on object-oriented thinking. ORM will It is converted/mapped into native SQL and handed over to pymysql for execution.

The emergence of ORM technology also allows us to write business logic code without spending a lot of energy to write complicated data access layer, and the corresponding CRUD operations can be handed over to the corresponding ORM plug-in to automatically generate code to complete.

SQLAlchemy uses

SQLAlchemy is the most famous ORM architecture in Python

Let's take an example of a simple integration of SQLAlchemy and Flask to see the basic use of SQLAlchemy

Install SQLAlchemy

pip install SQLAlchemy

Create a new Flask project, the project structure is as follows
insert image description here

Among them, students.py under the models folder stores the data table model, defines the object model mapping of the corresponding data table, each class represents a table, and the object of each class represents a row of tuples of the data table

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

# 创建对象的基类:
Base = declarative_base()

# 定义User对象:
class Student(Base):
    # 表的名字:
    __tablename__ = 'user'

    # 表的结构:
    id = Column(String(20), primary_key=True)
    name = Column(String(20))

config.py stores the corresponding config configuration of the Flask project. When there are many configuration items, the configuration items need to be written separately in a file, which is beneficial to project management, and can further integrate the development environment, test environment, and production environment. Distinguish between configuration

class Config:
    SECRET_KEY = "atuo_200"
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    SQLALCHEMY_TRACK_MODIFICATIONS = False

# 开发环境
class DevelopmentConfig(Config):
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/martdata'

# 测试环境
class TestingConfig(Config):
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/martdata'

# 生产环境
class ProductionConfig(Config):
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/martdata'


# 配置字典
config = {
    
    
    'development': DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,
    'default': DevelopmentConfig
}

app.py operates the corresponding data table model, obtains the data in the table, and sends it to the template for rendering and display

from flask import Flask,render_template
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
#导入存储配置的字典
from config import config
#导入数据表模型
from models.students import *

app = Flask(__name__)
app.config.from_object(config["development"])

#获取表中的数据,传送到模板利用jiaja进行渲染展示
@app.route("/")
def test():
    res = session1.query(Student).all()
    return render_template("index.html",res = res)

if __name__ == "__main__":
    engine = create_engine(app.config.get("SQLALCHEMY_DATABASE_URI"))
    # 创建DBSession类型:
    DBSession = sessionmaker(bind=engine)

    session1 = DBSession()
        #先把原来的数据表映射删除再创建
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    session1.add_all([
        Student(id = "1",name = "atuo"),Student(id = "2",name="帅坨"),Student(id = "3",name="小坨"),Student(id = "4",name="程洁"),Student(id = "5",name="阿坨")
    ])
        #过滤查询
    res_list = session1.query(Student).filter(Student.id < 2).all()
        #更新特定数据
    session1.query(Student).filter_by(name = "阿坨").update({
    
    "name":"阿坨坨"})
        #删除特定数据
    session1.query(Student).filter_by(name = "小坨").delete()
        #提交即保存至数据库
    session1.commit()
    app.run()

At this time, go to mysql to view the corresponding data table, and the corresponding data insertion, update, and deletion operations have been automatically completed, and we have not written any SQL statement (just open MySQL)

insert image description here

index.htmlcode

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>python之ORM</title>
</head>

<body>
    {% for i in res %}
    <h3>{
   
   { i.name }}</h3>
    {% endfor %}
</body>

</html>

insert image description here

Guess you like

Origin blog.csdn.net/atuo200/article/details/109761592