Mastering PyMySQL: Complete Guide to Python‑MySQL Integration
This article provides a comprehensive guide to using PyMySQL in Python, covering installation, connection setup, CRUD operations, transaction handling, advanced features like parameterized queries and connection pooling, as well as best practices for security, performance, and monitoring.
1. Introduction to PyMySQL
PyMySQL is a pure‑Python MySQL client library that implements the Python DB‑API v2.0, allowing developers to connect to MySQL, execute queries, and manage transactions.
2. Basic Usage
Install PyMySQL : pip install pymysql Create a connection :
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='testdb')Create a cursor : cursor = conn.cursor() Execute SQL :
cursor.execute("SELECT * FROM users WHERE age > %s", (25,))
rows = cursor.fetchall()
for row in rows:
print(row)Commit transactions : conn.commit() Close resources :
cursor.close()
conn.close()Using context manager :
with pymysql.connect(host='localhost', port=3306, user='root', password='password', database='testdb') as conn:
with conn.cursor() as cursor:
# perform operations
pass3. Advanced Features
Parameterized queries : use %s placeholders to prevent SQL injection.
Transaction management : conn.commit(), conn.rollback(), or enable autocommit=True.
Batch operations with cursor.executemany() for bulk inserts.
Charset and timezone settings in the connection: charset='utf8mb4', init_command='SET time_zone = "+08:00"'.
Error handling using try‑except blocks catching pymysql.MySQLError.
Connection pooling : integrate third‑party libraries such as DBUtils.
SQL injection protection and other security best practices.
Performance optimization : proper indexing, query tuning, pagination, caching.
Logging and monitoring : use Python’s logging module or tools like Loguru, Prometheus, Grafana.
4. Conclusion
PyMySQL offers a powerful, easy‑to‑use interface for Python developers to work with MySQL databases, supporting a wide range of features from basic CRUD to advanced transaction and performance optimizations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
