Python operates MySQL database
Python connects to MySQL database
In the Python 3 ecosystem, the mainstream MySQL driver libraries aremysqlclientandpymysqlTwo kinds. The APIs of the two are almost identical, and the only difference is the imported module name. We choose to implement it in pure Pythonpymysql, it does not require compilation of C extensions, and can be installed successfully on Windows, macOS, and Linux with one click. It is very suitable for novices to get started and is also capable of quickly setting up a production environment.
This tutorial uses pre-createdhrs(Human Resources) database is taken as an example to demonstrate step by step the complete process and code of Python operating MySQL.
Step 1: Environment preparation and connection process
Install dependencies
If your MySQL is version 5.x, only installpymysqlThat’s it; if you are connecting to MySQL 8.x, additional installation is required.cryptography, to support the new version’s defaultcaching_sha2_passwordAuthentication method.
Execute in the terminal (or PyCharm built-in Terminal):
Operation process sorting
pymysqlThe standard operation can be summarized into 5 core steps. We use the express delivery process to help remember:
- Establish Connection - Open up an exclusive channel between you and the warehouse, and tell the program the warehouse address, port, account password, database name and code.
- Get Cursor - Get the warehouse manager's "scanner", and all subsequent additions, deletions, modifications and searches will depend on it.
- Execute SQL command - Send specific SQL statements to the database through the cursor.
- Processing results or transactions — If it is a write operation (insert, delete, modify), it is required
commitConfirm to save, if any problem occursrollbackCancel; if it is a query, usefetchThe series method takes the data. - Close connection — Disconnect the connection immediately after use and release resources.
As long as you remember these five steps, you can quickly write schema-standard code for any database operation.
Step 2: Core Code Practice
Preparation: Create a dedicated database user
For security reasons, long-term use in production environments or learning is not recommended.rootSuper managed account. We first create a database in MySQL that only hashrsOrdinary users with basic library permissions:
Tips: The above operations require
rootThe account is executed in the MySQL command line or tools such as Navicat.
Insert a single piece of data
The following code simulates the scenario where the user enters department information and saves it to the database.
Efficiency Tips: If you want to insert thousands of pieces of data in batches, it is recommended to use
cursor.executemany(sql, data_list), the speed can be increased dozens of times.
Delete data
Demo starts here autocommit=True is suitable for simple scenarios of automatic submission of a single SQL statement (multi-step operations are not recommended for direct use).
Update data
Update operations still require manual transaction management to ensure data consistency.
Query data
pymysqlThree methods for extracting results are provided, which can be flexibly selected according to the amount of data:
fetchone(): Returns tuples row by row, with minimal memory overhead and suitable for large data sets.fetchmany(size=n): Get n records at a time.fetchall(): Returns all results at once, suitable for small data sets.
1. Ordinary cursor reads line by line
2. Dictionary cursor paging query
The default cursor returns tuple, and the field order depends on the SQL statement, which is not very readable. usepymysql.cursors.DictCursorThe results can be returned in the form of a dictionary, with the key name being the field name, which is more clear and intuitive.
Step 3: Practical Case—Export Data to Excel
In daily work, it is often necessary to export database tables into Excel reports. Pure Python is used here.openpyxllibrary to implement.
Install openpyxl
Export code
Goal: totb_empandtb_deptAfter natural connection, the employee’s job number, name, position, monthly salary, allowance, and department information are exported as员工表.xlsx。
After class exercises
Try the opposite: Batch import the data in the Excel file into the specified table in MySQL.
(Tip: Useopenpyxlofiter_rowsRead Excel content and combinecursor.executemany()Implement efficient batch insertion. )

