[100 days proficient in python] Day32: Use python to operate the database_MySQL download, installation, configuration, use actual combat

 Column Guide 

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


1 MySQL overview

        MySQL is an open source relational database management system widely used on the Internet. It was originally developed by the Swedish company MySQL AB and first released in 1995. Today, MySQL is maintained and supported by Oracle Corporation.

MySQL has many advantages, including:

1. Open source: MySQL is open source software, anyone can freely obtain, use and modify it.

2. Cross-platform: MySQL can run on multiple operating systems, including Windows, Linux, macOS, etc.

3. Flexibility: MySQL can be integrated with many programming languages ​​such as PHP, Java, Python, etc., making it ideal for developing web applications.

4. High performance: MySQL is designed to handle large-scale data and high concurrent requests, with fast response capability and efficient query engine.

5. Scalability : MySQL can be expanded horizontally and vertically as needed to support larger data volumes and higher loads.

6. Data integrity : MySQL supports transaction processing to ensure the consistency and integrity of data in concurrent operations.

        In addition to the above features, MySQL also has a wealth of functions and tools, such as index optimization, replication, backup and recovery mechanisms, and a highly compatible SQL language. 

        Because of its easy-to-use, stable and reliable features, and its free open source license, MySQL has become a popular database solution for web development and data storage. 

2 MySQL download and install

2.1 download

Open the link: MySQL :: Download MySQL Community Server

as follows:

Select MSI Installer:

As follows, select No thanks, just start my download. Select the specified folder to store it .


 2.2 Installation

After the download is complete, right-click and select Install, as follows 

Click Next: 

Select Next—>Typical—>Install:

 Select Typical:

Waiting for installation: 

 The installation is complete:


2.3 configuration

2.3.1 Service type and network configuration:

Click Finish to install and enter the configuration as follows:

Click Next——>

 As shown in the figure above, click the drop-down box of Config Type to display three types:

  • Development Computer : Development machine, MySQL will occupy the minimum amount of memory.
  • Server Computer : server machine, several server applications will run on the machine, suitable for database servers as websites or applications, and will take up medium memory.
  • Dedicated Computer : A dedicated machine, which is dedicated to running the MySQL database server and will occupy all available memory on the machine.

        Choose the corresponding type of configuration according to your own use. I will choose the "Server Machine" type for later high-concurrency performance testing.

2.3.2 Connection configuration:

After selecting the configuration type, proceed to the connection configuration, as shown in the figure below:

         Commonly used is TCP/IP connection, check this option box, the default port number is 3306, which can be changed in the input box. If the database is only used locally, you can check "Open Firewall port for network access" to open the firewall. If you need to call remotely, don't check it.
        The following "Named Pipe" and "Shared Memory" are inter-process communication mechanisms, which are generally unchecked.
        "Show Advanced Options" is used to configure advanced options in subsequent steps. In order to learn as much as possible about MySQL's configurable items, check this option box here.

2.3.3 Account and permission configuration:

Click next to enter the account configuration as follows:

 The root account has all the permissions of the database, and enter the password you set in the password box. During the development and maintenance of the database, for the sake of security and ease of management, different users will be granted account passwords with corresponding operation rights.

 Click the "Add User" button, and set accounts with different permission levels in the pop-up dialog box, as shown in the figure below:

 Host indicates the host address that can connect to the database, which can be set to local (localhost/127.0.0.1), an external IP (such as 218.17.224.228), an external network segment (such as 218.17.224.*) or all hosts (% ).
Role indicates the role of the account. The available roles are as above, and can be selected according to the needs. Set a password and click OK.

 You can add, delete, and edit related users.

2.3.4 Configure Windows Service:

Click next --> enter windows service


After the MySQL service is configured as a Windows service, the MySQL service will automatically start when the Windows operating system starts, and stop when the operating system stops. This is also the configuration recommended by the official MySQL documentation.

Windows service Name can be set as the default value, as long as it is different from other services. Based on the security requirements in the Windows system, the MySQL service needs to run under a given account, just select the default Standard System Account. Keep the default configuration and click "next".

2.3.5 Server file permission configuration:

 Permission configuration: as follows:

2.3.6 Create a dataset example

As follows: select create world database,

 Click next:

 After entering this step, click "Execute" to execute the configuration item, as shown below

  Click next, the following interface appears, the installation is successful, click Finish.


3 Using MySQL in python

        Since the MySQL server runs as an independent process and serves externally through the network, a MySQL driver that supports python is required to connect to the MySQL server.

        In Python, there are several commonly used third-party libraries that can be used to support interaction and operation with MySQL databases. The following are some of the main database modules that support MySQL:

  1. mysql-connector-python : This is the Python connection library officially provided by MySQL, which supports the connection, query and data operation of MySQL server.

  2. pymysql : It is a MySQL client library implemented in pure Python, which has better performance when interacting with MySQL.

  3. PyMySQL : Also a MySQL support library, similar to mysql-connector-python, but written in pure Python.

  4. SQLAlchemy : Although it is mainly used for ORM (object-relational mapping), it also supports connecting to MySQL databases and provides more advanced query and operation functions.

  5. MySQLdb : This is a popular MySQL client library in the Python 2.x era. Although it is no longer maintained, it may still be used in some legacy projects.

        The above libraries have different characteristics and usages, and you can choose the appropriate library according to your project requirements and personal preferences. In general, mysql-connector-pythonand pymysqlare the two most commonly used libraries in Python 3. Using these libraries, you can easily connect, manipulate and manage MySQL databases in Python. The following selects PyMySQL for usage instructions.

3.1 Install PyMySQL

        To install the PyMySQL library, you can use Python's package management tool pip.

        Here are the steps to install PyMySQL:

  1. Open a terminal or command line window.

  2. Run the following command to install PyMySQL:

pip install pymysql

 Wait for the installation to complete, you will see some output showing the progress and status of the installation.

After the installation is complete, you can import PyMySQL for use in Python scripts:  

        In this way, you have successfully installed the PyMySQL library, which can be used in your Python program to connect and operate the MySQL database. Note, make sure you have Python and pip installed on your computer, and you have sufficient privileges to do so.

        If you are using a virtual environment, perform the above steps in the virtual environment.

        After the installation is complete, you can use PyMySQL to connect and operate the MySQL database according to the previous examples.

3.2 Connect to the database

        The first step in using a database is to connect to the database. The following describes how to use PyMySQL to connect to the database.

         Connecting to a database using PyMySQL is very simple, here is a basic example showing how to connect to a MySQL database and perform some simple operations:

import pymysql

# 配置数据库连接参数
db_config = {
    "host": "localhost",
    "user": "username",
    "password": "password",
    "database": "mydb"
}

# 连接到数据库
conn = pymysql.connect(**db_config)

# 创建游标对象
cursor = conn.cursor()

# 执行查询语句
query = "SELECT * FROM users"
cursor.execute(query)

# 获取查询结果
rows = cursor.fetchall()
for row in rows:
    print(row)

# 关闭游标和连接
cursor.close()
conn.close()

        In this example, we first configure the parameters to connect to the database, and then use pymysql.connect()the function to create the connection object conn. Next, we use to conn.cursor()create a cursor object cursor, then execute the query statement, get the query result and output it.

        This is just a simple join and query example. According to your needs, you can use to cursor.execute()execute other SQL statements, such as insert, update, delete and other operations. In practice, however, it is important to implement error handling, ensure connections and cursors are properly closed, and follow best practices for safe and performant database operations.

3.3 Create a data table

        In PyMySQL, you can use the way of executing SQL statements to create data tables for the database. Here is an example showing how to create a table called "users" using PyMySQL:

import pymysql

# 配置数据库连接参数
db_config = {
    "host": "localhost",
    "user": "username",
    "password": "password",
    "database": "mydb"
}

# 连接到数据库
conn = pymysql.connect(**db_config)

# 创建游标对象
cursor = conn.cursor()

# 创建数据表
create_table_query = """
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL
)
"""
cursor.execute(create_table_query)

# 提交创建表的操作
conn.commit()

# 关闭游标和连接
cursor.close()
conn.close()

In this example, we use pymysql.connect()the function to connect to the database, and then conn.cursor()create the cursor object using the . Next, we use to cursor.execute()execute the SQL statement to create a data table named "users". The structure of a table CREATE TABLEis defined in a statement, which includes column names, data types, and constraints. Finally, we commit conn.commit()the table creation operation with and close the cursor and connection.

Note that this is just an example. In practice, you may need more columns and more complex structures. Make sure you understand database design principles and conventions to create data tables appropriate for your application

3.4 Operate MySQL data table

After you connect to the MySQL database, you can perform various operations to manage the data tables. The following are examples of some common operations, including inserting, querying, updating, and deleting data in a data table.

3.4.1 Insert data:
import pymysql

# 配置数据库连接参数
db_config = {
    "host": "localhost",
    "user": "username",
    "password": "password",
    "database": "mydb"
}

# 连接到数据库
conn = pymysql.connect(**db_config)

# 创建游标对象
cursor = conn.cursor()

# 插入数据
insert_query = "INSERT INTO users (username, email) VALUES (%s, %s)"
values = ("alice", "[email protected]")
cursor.execute(insert_query, values)

# 提交插入数据的操作
conn.commit()

# 关闭游标和连接
cursor.close()
conn.close()
3.4.2 Query data:
import pymysql

# 配置数据库连接参数
db_config = {
    "host": "localhost",
    "user": "username",
    "password": "password",
    "database": "mydb"
}

# 连接到数据库
conn = pymysql.connect(**db_config)

# 创建游标对象
cursor = conn.cursor()

# 查询数据
select_query = "SELECT * FROM users"
cursor.execute(select_query)

# 获取查询结果
rows = cursor.fetchall()
for row in rows:
    print(row)

# 关闭游标和连接
cursor.close()
conn.close()
3.4.3 Update data:
import pymysql

# 配置数据库连接参数
db_config = {
    "host": "localhost",
    "user": "username",
    "password": "password",
    "database": "mydb"
}

# 连接到数据库
conn = pymysql.connect(**db_config)

# 创建游标对象
cursor = conn.cursor()

# 更新数据
update_query = "UPDATE users SET email = %s WHERE username = %s"
new_email = "[email protected]"
username = "alice"
cursor.execute(update_query, (new_email, username))

# 提交更新数据的操作
conn.commit()

# 关闭游标和连接
cursor.close()
conn.close()
3.4.4 Delete data:
import pymysql

# 配置数据库连接参数
db_config = {
    "host": "localhost",
    "user": "username",
    "password": "password",
    "database": "mydb"
}

# 连接到数据库
conn = pymysql.connect(**db_config)

# 创建游标对象
cursor = conn.cursor()

# 删除数据
delete_query = "DELETE FROM users WHERE username = %s"
username = "alice"
cursor.execute(delete_query, (username,))

# 提交删除数据的操作
conn.commit()

# 关闭游标和连接
cursor.close()
conn.close()

        These examples show how to use PyMySQL to perform insert, query, update and delete data in data tables. Note that in practice, it is important to implement error handling, ensure connections and cursors are properly closed, and follow best practices for safe and performant database operations.

4 MySQL usage in practice

        Create a database, then create a "books" table in the database, get the information in the specified data table, and print the names and prices of books in the books table in MySQL.

The following is an example showing how to use PyMySQL to create a database, create tables, and insert and query data:

import pymysql

# 配置数据库连接参数
db_config = {
    "host": "localhost",
    "user": "aaaa",  #your_username
    "password": "lucky"  #your_password
}

def create_database_and_table(cursor):
    # 创建数据库
    cursor.execute("CREATE DATABASE IF NOT EXISTS mydb")
    cursor.execute("USE mydb")

    # 创建数据表
    create_table_query = """
    CREATE TABLE IF NOT EXISTS books (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        price DECIMAL(10, 2) NOT NULL
    )
    """
    cursor.execute(create_table_query)

def insert_sample_data(cursor):
    # 插入示例数据
    insert_query = "INSERT INTO books (name, price) VALUES (%s, %s)"
    values = [("Book A", 19.99), ("Book B", 29.99), ("Book C", 9.99)]
    cursor.executemany(insert_query, values)

def print_books_info(cursor):
    # 查询图书名称和价格
    select_query = "SELECT name, price FROM books"
    cursor.execute(select_query)

    # 获取查询结果
    rows = cursor.fetchall()

    # 打印图书名称和价格
    for row in rows:
        book_name, book_price = row
        print(f"Book Name: {book_name}, Price: {book_price}")

def main():
    # 连接到数据库
    conn = pymysql.connect(**db_config)

    # 创建游标对象
    cursor = conn.cursor()

    try:
        # 创建数据库和数据表
        create_database_and_table(cursor)

        # 插入示例数据
        insert_sample_data(cursor)
        conn.commit()

        # 打印图书信息
        print_books_info(cursor)

    finally:
        # 关闭游标和连接
        cursor.close()
        conn.close()

if __name__ == "__main__":
    main()

        In this example, we first created a database "mydb" and then created the "books" table in that database. Make sure you replace "your_username" and "your_password" with your actual database username and password. Before running the code, make sure you have installed the PyMySQL library (via pip install pymysql). 

 The output is as follows:

 Run the above code, if there is an error

RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods

Indicates that your Python environment cryptographyis missing the package that supports the sha256_passwordor caching_sha2_passwordauthentication methods for the MySQL database. To fix this, you can follow the steps below to install cryptographythe package:

  1. Open a terminal or command line window.

  2. Run the following command to install cryptographythe package:

    pip install cryptography
    

Guess you like

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