python:chapter33

第三十三章:MySQL数据库

完成本章学习后,你将能够:

  • 使用pymysql连接MySQL
  • 执行增删改查
  • 使用连接池
import pymysql
 
# 连接数据库
conn = pymysql.connect(
    host='localhost',
    user='user',
    password='password',
    database='mydb',
    charset='utf8mb4'
)
 
try:
    with conn.cursor() as cursor:
        # 创建表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(100),
                email VARCHAR(100)
            )
        ''')
 
        # 插入
        cursor.execute(
            "INSERT INTO users (name, email) VALUES (%s, %s)",
            ("Alice", "alice@example.com")
        )
        conn.commit()
 
        # 查询
        cursor.execute("SELECT * FROM users")
        results = cursor.fetchall()
        for row in results:
            print(row)
finally:
    conn.close()
from pymysqlpool import ConnectionPool
 
config = {
    'host': 'localhost',
    'user': 'user',
    'password': 'password',
    'database': 'mydb'
}
 
pool = ConnectionPool(size=10, name='mypool', **config)

1. 实现MySQL CRUD操作 2. 使用连接池优化性能 3. 实现读写分离

下一章:第三十四章:ORM与SQLAlchemy

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • python/chapter33.txt
  • 最后更改: 2026/04/09 14:41
  • 张叶安