Learn python from scratch with me (4) database programming: MySQL database

foreword

Looking back, I talked about python syntax programming, compulsory introductory basics and network programming, multi-threading/multi-process/coroutine, etc. Today, I have come to the database programming chapter. If you haven’t read it before, you don’t need to go forward. The series of articles have been sorted out. :

1. Learn python from scratch with me (1) Compulsory programming grammar
2. Learn python from scratch with me (2) Network programming
3. Learn python from scratch with me (3) Multi-thread/multi-process/ coroutine

This article talks about: Python database programming: MySQL database

insert image description here

This series of articles is based on the following learning routes. Due to the large content:

Learn python from scratch to advanced advanced roadmap

Pay attention to the official account: python technology training camp , learn advanced step by step

Python resources suitable for zero-based learning and advanced people:

① Tencent certified python complete project practical tutorial notes PDF
② More than a dozen major manufacturers python interview topic PDF
③ Python full set of video tutorials (zero foundation-advanced advanced JS reverse)
④ Hundreds of project actual combat + source code + notes
⑤ Programming grammar - machine learning -Full-stack development-data analysis-crawler-APP reverse engineering and other full set of projects + documents
⑥ Exchange and study
⑦ Want to take part-time orders

The next chapter: Redis database

1. MySQL database

MySQL database

1. MySQL basics

MySQL is a relational database management system and one of the most popular open source databases. Python can connect to and operate MySQL databases through modules such as MySQLdb and PyMySQL.

The following are the basic steps for Python to connect to the MySQL database:

Install the MySQLdb or PyMySQL module

    pip install MySQLdb

or

    pip install PyMySQL

import module

    import MySQLdb

or

    import pymysql

Connect to the database

    # MySQLdb模块
    conn = MySQLdb.connect(host='localhost', user='root', password='password', database='test', port=3306)
    
    # PyMySQL模块
    conn = pymysql.connect(host='localhost', user='root', password='password', database='test', port=3306)

Create a cursor object

    cursor = conn.cursor()

Execute SQL statement

    cursor.execute('SELECT * FROM table_name')

Get query results

    result = cursor.fetchall()

close cursor and connection

    cursor.close()
    conn.close()

The above are the basic steps for Python to connect to the MySQL database, and the specific operations can be adjusted according to actual needs.

2. In MySQL database, common data types include :

  • Numerical type : Including integer, floating point, double precision, etc.

  • String type : including fixed-length string, variable-length string, text type, etc.

  • Date and time types : including date, time, datetime, etc.

  • Boolean type : includes both true and false values.

  • Binary type : including binary data, image, audio, etc.

  • Enumerated type : includes a set of predefined values.

  • Collection Type : Includes a predefined set of values, but more than one can be selected.

In Python, you can use libraries such as MySQLdb or pymysql to connect to the MySQL database, and use SQL statements to create, modify, query, and delete data tables. When creating a data table, you need to specify the data type of each field to ensure the correctness and integrity of the data.

3. In a MySQL database, a constraint is a rule used to limit the data in a table. The following are commonly used constraints in MySQL :

  • NOT NULL constraint : This constraint is used to ensure that the values ​​in the column are not null.

  • UNIQUE constraint : This constraint is used to ensure that the values ​​in the column are unique.

  • PRIMARY KEY constraint : This constraint is used to set the column as the primary key to ensure that each row of data has a unique identifier.

  • FOREIGN KEY constraint : This constraint is used to ensure that the values ​​in a column match the values ​​in another table, and is usually used to establish relationships between tables.

  • CHECK constraint : This constraint is used to ensure that the values ​​in the column meet the specified conditions.

  • DEFAULT Constraint : This constraint is used to provide a default value for a column when a new row is inserted.

For example, the following is an example of a MySQL table with constraints:

    CREATE TABLE students (
      id INT PRIMARY KEY,
      name VARCHAR(50) NOT NULL,
      age INT CHECK (age >= 18),
      email VARCHAR(50) UNIQUE,
      major_id INT,
      FOREIGN KEY (major_id) REFERENCES majors(id)
    );

In the example above, the id column is set as the primary key, ensuring that each row of data has a unique identifier. The name column is set to NOT NULL to ensure that the value in this column is not null. The age column is set as a CHECK constraint to ensure that the values ​​in this column are greater than or equal to 18. The email column is set as a UNIQUE constraint, ensuring that the values ​​in this column are unique. major\_idThe column is set as a FOREIGN KEY constraint, ensuring that the values ​​in this column match the id column in the majors table.

4. To operate the MySQL database in Python, you need to use third-party libraries such as MySQLdb or pymysql

Some basic database operations are described below.

  • Connecting to the database
    The code to connect to the database using the MySQLdb library is as follows:
    import MySQLdb
    
    # 打开数据库连接
    db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="test")
    
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    
    # 关闭数据库连接
    db.close()

The code to connect to the database using the pymysql library is as follows:

    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", passwd="password", db="test")
    
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    
    # 关闭数据库连接
    db.close()
  • Create tables
    Use execute()methods to execute SQL statements to create tables, for example:
    # 创建表
    sql = """CREATE TABLE EMPLOYEE (
             FIRST_NAME  CHAR(20) NOT NULL,
             LAST_NAME  CHAR(20),
             AGE INT,
             SEX CHAR(1),
             INCOME FLOAT )"""
    
    cursor.execute(sql)
  • Insert data
    Use execute()methods to execute SQL statements to insert data, for example:
    # 插入数据
    sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
             LAST_NAME, AGE, SEX, INCOME)
             VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
    
    cursor.execute(sql)
  • Query data
    Use execute()methods to execute SQL statements to query data, for example:
    # 查询数据
    sql = "SELECT * FROM EMPLOYEE WHERE INCOME > %s" % (1000)
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % (fname, lname, age, sex, income))
  • Update data
    Use execute()methods to execute SQL statements to update data, for example:
    # 更新数据
    sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
    cursor.execute(sql)
  • Delete data
    Use execute()methods to execute SQL statements to delete data, for example:
    # 删除数据
    sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
    cursor.execute(sql)

5. In MySQL, the data table is the basic unit for storing data.
The following introduces some commonly used data table operations.

  • Create a data table
    The syntax for creating a data table is as follows:
    CREATE TABLE table_name (
       column1 datatype,
       column2 datatype,
       column3 datatype,
       .....
    );

Among them, table\_nameis the name of the data table to be created, column1, column2, column3, etc. are the column names in the data table, and datatype is the data type of the column.

For example, to create a data table named students, which contains three columns of id, name, and age, and the data types are int, varchar(20), and int, the following statement can be used:

    CREATE TABLE students (
       id int,
       name varchar(20),
       age int
    );
  • Inserting data
    The syntax for inserting data is as follows:
    INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);

Among them, table\_nameis the name of the data table to insert data, column1, column2, column3, etc. are the column names in the data table, and value1, value2, value3, etc. are the data to be inserted.

For example, to insert a piece of data into the students data table, the id is 1, the name is "Tom", and the age is 18, you can use the following statement:

    INSERT INTO students (id, name, age) VALUES (1, 'Tom', 18);
  • Querying Data
    The syntax for querying data is as follows:
    SELECT column1, column2, column3, ... FROM table_name WHERE condition;

Among them, table\_nameis the name of the data table whose data is to be queried, column1, column2, column3, etc. are the column names to be queried, and condition is the query condition.

For example, to query all the data in the students data table, you can use the following statement:

    SELECT * FROM students;
  • Updating Data
    The syntax for updating data is as follows:
    UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;

Among them, table\_name is the name of the data table whose data is to be updated, column1, column2, etc. are the column names to be updated, value1, value2, etc. are the values ​​to be updated, and condition is the update condition.

For example, to update the age of the record with id 1 in the students data table to 20, you can use the following statement:

    UPDATE students SET age = 20 WHERE id = 1;
  • Deleting Data
    The syntax for deleting data is as follows:
    DELETE FROM table_name WHERE condition;

Among them, table\_nameis the name of the data table whose data is to be deleted, and condition is the deletion condition.

For example, to delete the record whose id is 1 in the students data table, you can use the following statement:

    DELETE FROM students WHERE id = 1;
  • Deleting a Data Table
    The syntax for deleting a data table is as follows:
    DROP TABLE table_name;

where table\_nameis the name of the data table to delete.

For example, to delete the students data table, you can use the following statement:

    DROP TABLE students;

6. The basic operation of adding, deleting, modifying and checking MySQL database with Python is as follows :

  • Connect to the database
    Use the pymysql library in Python to connect to the MySQL database. The sample code is as follows:
    import pymysql

    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
    
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    
    # 关闭数据库连接
    db.close()
  • Create a data table
    Use the pymysql library in Python to create a data table in the MySQL database. The sample code is as follows:
    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
    
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    
    # 创建数据表SQL语句
    sql = """CREATE TABLE EMPLOYEE (
             FIRST_NAME  CHAR(20) NOT NULL,
             LAST_NAME  CHAR(20),
             AGE INT,  
             SEX CHAR(1),
             INCOME FLOAT )"""
    
    # 执行SQL语句
    cursor.execute(sql)
    
    # 关闭数据库连接
    db.close()
  • Insert data
    Use the pymysql library in Python to insert data into the data table in the MySQL database. The sample code is as follows:
    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
    
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    
    # SQL 插入语句
    sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
             LAST_NAME, AGE, SEX, INCOME)
             VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
    
    # 执行SQL语句
    cursor.execute(sql)
    
    # 提交到数据库执行
    db.commit()
    
    # 关闭数据库连接
    db.close()
  • Query data
    Use the pymysql library in Python to query data from the data tables in the MySQL database. The sample code is as follows:
    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
    
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    
    # SQL 查询语句
    sql = "SELECT * FROM EMPLOYEE \
           WHERE INCOME > %s" % (1000)
    
    # 执行SQL语句
    cursor.execute(sql)
    
    # 获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        # 打印结果
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % (fname, lname, age, sex, income))
    
    # 关闭数据库连接
    db.close()
  • Update data
    Use the pymysql library in Python to update the data table data in the MySQL database. The sample code is as follows:
    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
    
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    
    # SQL 更新语句
    sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
    
    # 执行SQL语句
    cursor.execute(sql)
    
    # 提交到数据库执行
    db.commit()
    
    # 关闭数据库连接
    db.close()
  • Delete data
    Use the pymysql library in Python to delete the data table data in the MySQL database. The sample code is as follows:
    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
    
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    
    # SQL 删除语句
    sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
    
    # 执行SQL语句
    cursor.execute(sql)
    
    # 提交到数据库执行
    db.commit()
    
    # 关闭数据库连接
    db.close()

2. MySQL advanced query

1. Create database, data table

  • Create a database:

Use Python to connect to the MySQL database, you can use mysql.connectorthe module, the sample code is as follows:

    import mysql.connector
    
    # 连接MySQL数据库
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      password="123456"
    )
    
    # 创建数据库
    mycursor = mydb.cursor()
    mycursor.execute("CREATE DATABASE mydatabase")
  • Create a data table:

Use Python to connect to the MySQL database, you can use mysql.connectorthe module, the sample code is as follows:

    import mysql.connector
    
    # 连接MySQL数据库
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      password="123456",
      database="mydatabase"
    )
    
    # 创建数据表
    mycursor = mydb.cursor()
    mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

The above code creates a customersdata table named, which contains two fields nameand address, both of typeVARCHAR(255)

2. Condition query

Conditional query refers to filtering out the data that meets the requirements according to certain conditions. Commonly used conditional query statements include WHERE, AND, OR, IN, BETWEEN, etc.

  • WHERE statement
    The WHERE statement is used to specify query conditions, the syntax is as follows:
    SELECT column1, column2, ... FROM table_name WHERE condition;

Among them, condition is the query condition, you can use comparison operators (=, <, >, <=, >=, <>), logic operators (AND, OR, NOT) and wildcards (%, _), etc.

For example, to query the information of students whose age is greater than or equal to 18:

    SELECT * FROM students WHERE age >= 18;
  • AND statement The
    AND statement is used to satisfy multiple conditions at the same time, the syntax is as follows:
    SELECT column1, column2, ... FROM table_name WHERE condition1 AND condition2 AND ...;

For example, to query the information of students whose age is greater than or equal to 18 and whose gender is female:

SELECT * FROM students WHERE age >= 18 AND gender = '女';
  • OR statement
    The OR statement is used to satisfy any one of multiple conditions. The syntax is as follows:
    SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR ...;

For example, to query the information of students whose age is greater than or equal to 18 or whose gender is female:

    SELECT * FROM students WHERE age >= 18 OR gender = '女';
  • IN statement
    The IN statement is used to specify multiple values, the syntax is as follows:
    SELECT column1, column2, ... FROM table_name WHERE column_name IN (value1, value2, ...);

For example, to query the student information of student numbers 1001, 1002, and 1003:

    SELECT * FROM students WHERE id IN (1001, 1002, 1003);
  • BETWEEN statement
    BETWEEN statement is used to specify a range, the syntax is as follows:
    SELECT column1, column2, ... FROM table_name WHERE column_name BETWEEN value1 AND value2;

For example, to query student information between the ages of 18 and 20:

    SELECT * FROM students WHERE age BETWEEN 18 AND 20;

The above is the basic syntax of conditional query, which can be flexibly used according to actual needs.

3. In MySQL, you can use the ORDER BY clause to sort the query results

The ORDER BY clause can be followed by one or more column names, separated by commas. By default, the sorting is ascending, and the DESC keyword can be used for descending sorting.

For example, the following statement will sort in ascending order by the age column:

    SELECT * FROM students ORDER BY age;

The following statement will sort in descending order by the age column:

    SELECT * FROM students ORDER BY age DESC;

You can specify multiple columns to sort at the same time, for example:

    SELECT * FROM students ORDER BY grade DESC, age;

The above statement will first sort in descending order according to the grade column, and if there are the same grade values, then sort in ascending order according to the age column.

Note that the ORDER BY clause should be placed at the end of the query statement.

4. In MySQL, grouping is an operation of classifying data according to a certain field

Grouping can be used for statistical data, calculating the value of aggregate functions such as average, maximum, minimum, etc.

Here's a simple example, assuming we have a students table with names, ages and grades of students:

    CREATE TABLE students (
        id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(50),
        age INT,
        score INT
    );
    
    INSERT INTO students (name, age, score) VALUES
        ('Tom', 18, 90),
        ('Jerry', 19, 80),
        ('Lucy', 18, 95),
        ('Lily', 20, 85),
        ('Bob', 19, 75);

Now we want to group by age and count the average grade and highest grade of each age group, we can use the following SQL statement:

    SELECT age, AVG(score) AS avg_score, MAX(score) AS max_score
    FROM students
    GROUP BY age;

The execution results are as follows:

    +-----+-----------+----------+
    | age | avg_score | max_score |
    +-----+-----------+----------+
    |  18 | 92.5000   |       95 |
    |  19 | 77.5000   |       80 |
    |  20 | 85.0000   |       85 |
    +-----+-----------+----------+

As you can see, we have grouped by age and counted the average and highest scores for each age group.

In the group query, we can also use the HAVING clause to filter the grouped data. For example, if we want to find out the age group whose average score is greater than 85, we can use the following SQL statement:

    SELECT age, AVG(score) AS avg_score
    FROM students
    GROUP BY age
    HAVING avg_score > 85;

The execution results are as follows:

    +-----+-----------+
    | age | avg_score |
    +-----+-----------+
    |  18 | 92.5000   |
    |  20 | 85.0000   |
    +-----+-----------+

It can be seen that we only keep the age group whose average score is greater than 85 points.

3. MySQL advanced application

1. view

In MySQL, a view is a virtual table composed of query results from one or more basic tables. Views do not store data, but dynamically generate result sets based on query statements. Views can simplify complex query operations, improve query efficiency, and protect data security.

The syntax for creating a view is as follows:

    CREATE VIEW view_name AS
    SELECT column1, column2, ...
    FROM table_name
    WHERE condition;

Among them, view_nameis the name of the view, column1, column2, ...is the name of the column to be queried, table_nameis the name of the table to be queried, and conditionis the query condition.

For example, we can create a employee_viewview called , that queries the , and columns employeeof the table :idnamesalary

    CREATE VIEW employee_view AS
    SELECT id, name, salary
    FROM employee;

The syntax for querying a view is similar to that for querying a table:

    SELECT * FROM view_name;

For example, we can query employee_viewthe results of a view:

    SELECT * FROM employee_view;

Views can also be updated, but certain conditions need to be met. Specifically, views can perform the following types of update operations:

  • Updates are made to single-table views, that is, views that involve only one base table.
  • Update a multi-table view, but the update operation can only involve certain columns of a basic table, and these columns must be unique.
    The syntax for updating a view is as follows:
    UPDATE view_name
    SET column1 = value1, column2 = value2, ...
    WHERE condition;

For example, we can update employee_viewthe salary of employee with id 1 in the view:

    UPDATE employee_view
    SET salary = 5000
    WHERE id = 1;

It should be noted that when a view is updated, the data in the base table is actually updated, not the view itself. Therefore, the constraints of the basic table must be met when updating the view, otherwise the update will fail.

In addition to update operations, views can also perform insert and delete operations, and the specific syntax is similar to table operations. However, it should be noted that insert and delete operations can only involve one basic table, and the constraints of the basic table must be met.

2. Affairs

A transaction is a set of operations that either all execute successfully or none of them execute. In MySQL, transactions use ACID properties to ensure data consistency and reliability.

ACID refers to:

  • Atomicity : All operations in a transaction are either executed successfully or not executed at all.
  • Consistency : Before and after the execution of the transaction, the integrity and constraints of the data remain unchanged.
  • Isolation : Transactions are isolated from each other, and the execution of one transaction will not affect the execution of other transactions.
  • Durability : Once a transaction is committed, the modification to the data is permanent and will not be lost even if the system crashes.

In MySQL, use the BEGIN, COMMIT, and ROLLBACK statements to control the commit and rollback of transactions.

  • BEGIN : Begins a transaction.
  • COMMIT : Commits a transaction and permanently saves all operations in the transaction to the database.
  • ROLLBACK : Roll back a transaction, undoing all operations in the transaction.
    Here is an example using transactions:
    import mysql.connector
    
    # 连接数据库
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      password="123456",
      database="mydatabase"
    )
    
    # 获取游标
    mycursor = mydb.cursor()
    
    # 开始事务
    mycursor.execute("START TRANSACTION")
    
    # 执行操作
    try:
      sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
      val = ("John", "Highway 21")
      mycursor.execute(sql, val)
    
      sql = "UPDATE customers SET address = 'Park Lane 38' WHERE address = 'Highway 21'"
      mycursor.execute(sql)
    
      # 提交事务
      mydb.commit()
    
    except:
      # 回滚事务
      mydb.rollback()
    
    # 关闭连接
    mydb.close()

In the above example, we used START TRANSACTION to start a transaction, and then performed two operations: inserting a piece of data and updating a piece of data. If both operations are performed successfully, COMMIT is used to commit the transaction, otherwise ROLLBACK is used to roll back the transaction.

3. Use of pyMySQL

pyMySQL is a third-party library in Python for connecting to MySQL databases. It provides some easy-to-use APIs for convenient database operations.

  • Install pyMySQL:

It can be installed using the pip command:

    pip install pymysql
  • Connect to the MySQL database:

Before using pyMySQL, you need to connect to the MySQL database first. To connect to the MySQL database, you need to specify information such as the host name, user name, password, and database name. The following code can be used to connect:

    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", password="password", database="test")
    
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    
    # 关闭数据库连接
    db.close()

Among them, host represents the host name, user represents the user name, password represents the password, and database represents the name of the database to be connected.

  • Execute the SQL statement:

After connecting to the MySQL database, you can use the cursor object to execute SQL statements. pyMySQL supports the execution of all SQL statements, including query, insert, update, delete and other operations. The following is an example query operation:

    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", password="password", database="test")
    
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    
    # 执行SQL语句
    sql = "SELECT * FROM students"
    cursor.execute(sql)
    
    # 获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        id = row[0]
        name = row[1]
        age = row[2]
        gender = row[3]
        print("id=%d,name=%s,age=%d,gender=%s" % (id, name, age, gender))
    
    # 关闭数据库连接
    db.close()

Before executing the SQL statement, you need to use cursor()the method to obtain the operation cursor. Executing SQL statements can use execute()the method, which accepts an SQL statement as a parameter. The query operation can use fetchall()the method to get a list of all records, and then traverse each record.

Insert, update, and delete operations can also use execute()methods, just pass in the corresponding SQL statement as a parameter.

The above is the basic usage of pyMySQL. For more detailed API, please refer to the official documentation.

4. MySQL ORM framework-SQLAIchemy

SQLAlchemy is a Python SQL toolkit and ORM framework that provides an extensive set of tools that make working with SQL in Python easier and more flexible. The main goal of SQLAlchemy is to provide efficient and high-performance access to SQL databases, and supports a variety of relational databases, such as MySQL, PostgreSQL, Oracle, Microsoft SQL Server, etc.

SQLAlchemy's ORM framework provides a way to map Python objects to relational database tables, allowing developers to use the Python language to operate the database without having to use the SQL language directly. The ORM framework can automatically create database tables, insert data, update data, delete data and other operations, and also supports advanced functions such as transactions, connection pools, and caches.

Here is an example using the SQLAlchemy 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('mysql+pymysql://username:password@host:port/database')
    
    # 创建Session类
    Session = sessionmaker(bind=engine)
    
    # 创建Base类
    Base = declarative_base()
    
    # 定义User类
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(String(50))
        age = Column(Integer)
    
    # 创建表
    Base.metadata.create_all(engine)
    
    # 创建Session实例
    session = Session()
    
    # 插入数据
    user = User(name='Tom', age=20)
    session.add(user)
    session.commit()
    
    # 查询数据
    users = session.query(User).all()
    for user in users:
        print(user.name, user.age)
    
    # 更新数据
    user = session.query(User).filter_by(name='Tom').first()
    user.age = 21
    session.commit()
    
    # 删除数据
    user = session.query(User).filter_by(name='Tom').first()
    session.delete(user)
    session.commit()
    
    # 关闭Session
    session.close()

In the above example, we first created a database connection, then created a Session class and a Base class. The Session class is used to create Session instances, and the Base class is used to define the ORM mapping relationship. We define a User class, which inherits from the Base class, and defines the table name and fields. Then we Base.metadata.create_all()created the table using the method. Then we created a Session instance and used session.add()the method to insert a piece of data. Use session.query()methods to query data, and session.commit()methods to commit transactions. We also demonstrate how to update and delete data, and finally use session.close()the method to close Session.

The SQLAlchemy ORM framework provides rich features and flexible configuration options to meet various needs. At the same time, it also has a certain learning curve and takes some time to learn and master.

1. An example of using SQLAlchemy to query a MySQL database

First, the SQLAlchemy library needs to be installed:

    pip install sqlalchemy

Then, connect to the MySQL database:

    from sqlalchemy import create_engine

    # 连接MySQL数据库
    engine = create_engine('mysql+pymysql://username:password@host:port/database')

Among them, usernameand passwordis the username and password of the MySQL database, hostis the host name of the MySQL database, portis the port number of the MySQL database, databaseand is the name of the database to be connected.

Next, define an ORM model:

    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, String
    
    # 定义ORM模型
    Base = declarative_base()
    
    class User(Base):
        __tablename__ = 'users'
    
        id = Column(Integer, primary_key=True)
        name = Column(String(50))
        age = Column(Integer)

This ORM model corresponds to the users table in the MySQL database, including three fields id, nameand age.

Next, query the data using SQLAlchemy:

    from sqlalchemy.orm import sessionmaker
    
    # 创建Session
    Session = sessionmaker(bind=engine)
    session = Session()
    
    # 查询所有用户
    users = session.query(User).all()
    for user in users:
        print(user.id, user.name, user.age)
    
    # 查询年龄大于等于18岁的用户
    users = session.query(User).filter(User.age >= 18).all()
    for user in users:
        print(user.id, user.name, user.age)
    
    # 查询年龄大于等于18岁的用户,并按照年龄从小到大排序
    users = session.query(User).filter(User.age >= 18).order_by(User.age).all()
    for user in users:
        print(user.id, user.name, user.age)

The above code respectively queries all users, users whose age is greater than or equal to 18 years old, and users whose age is greater than or equal to 18 years old, and sorts the results in ascending order of age, and prints them out.

In addition to the above examples, SQLAlchemy also supports more query methods, such as pagination query, aggregation query, etc.

The above is about the content analysis of python database programming MySQL database

This series of articles is based on the following learning routes. Due to the large content:

Learn python from scratch to advanced advanced roadmap

Pay attention to the official account: python technology training camp , learn advanced step by step

Python resources suitable for zero-based learning and advanced people:

① Tencent certified python complete project practical tutorial notes PDF
② More than a dozen major manufacturers python interview topic PDF
③ Python full set of video tutorials (zero foundation-advanced advanced JS reverse)
④ Hundreds of project actual combat + source code + notes
⑤ Programming grammar - machine learning -Full-stack development-data analysis-crawler-APP reverse engineering and other full set of projects + documents
⑥ Exchange and study
⑦ Want to take part-time orders

The next chapter: Redis database

Guess you like

Origin blog.csdn.net/ch950401/article/details/131623120