Python编程——进阶知识(MYSQL引导入门)

目录

前言

一、环境配置

[二、CRUD 全流程](#二、CRUD 全流程)

三、事务管理:确保数据一致性

四、技巧与建议

[五、SQLAlchemy(ORM 推荐)](#五、SQLAlchemy(ORM 推荐))

六、安全与性能

小结


前言

在现代数据驱动的应用开发中,Python 与 MySQL 的组合因其简洁、高效、稳定而广受欢迎。无论是 Web 后端、数据分析还是自动化脚本,掌握 Python 操作 MySQL 的技能都至关重要。本文将带你从零开始,系统学习如何使用 Python 安全、高效地连接、查询和管理 MySQL 数据库。


一、环境配置

1. PyMySQL

复制代码
pip install PyMySQL

2. 基本连接

python 复制代码
import pymysql

# 创建数据库连接
connection = pymysql.connect(
    host='localhost',
    user='testuser',
    password='test123',
    database='TESTDB',
    charset='utf8mb4',  # 推荐使用 utf8mb4 支持 emoji
    cursorclass=pymysql.cursors.DictCursor  # 返回字典而非元组
)

try:
    with connection.cursor() as cursor:
        cursor.execute("SELECT VERSION()")
        version = cursor.fetchone()
        print(f"Database version: {version['VERSION()']}")
finally:
    connection.close()

建议: 使用 with 语句自动管理游标,确保资源释放。


二、CRUD 全流程

1. 创建表(Create)

python 复制代码
create_table_sql = """
CREATE TABLE IF NOT EXISTS EMPLOYEE (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50),
    age INT,
    sex CHAR(1),
    income DECIMAL(10, 2)
)
"""

with connection.cursor() as cursor:
    cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
    cursor.execute(create_table_sql)
    connection.commit()

2. 插入数据(Insert)

python 复制代码
insert_sql = """
INSERT INTO EMPLOYEE (first_name, last_name, age, sex, income)
VALUES (%s, %s, % s, %s, %s)
"""

with connection.cursor() as cursor:
    cursor.execute(insert_sql, ('Mac', 'Mohan', 20, 'M', 2000.0))
    connection.commit()
    print(f"Inserted record ID: {cursor.lastrowid}")

注意(SQL注入风险):

复制代码
# 危险!易受 SQL 注入攻击
cursor.execute(f"INSERT ... VALUES ({name}, {age})")

3. 查询数据(Read)

python 复制代码
query_sql = "SELECT * FROM EMPLOYEE WHERE income > %s"

with connection.cursor() as cursor:
    cursor.execute(query_sql, (1000,))
    results = cursor.fetchall()
    
    for row in results:
        print(f"Name: {row['first_name']} {row['last_name']}, Income: {row['income']}")
  • fetchone():获取单条记录
  • fetchall():获取所有记录
  • fetchmany(n):获取 n 条记录

4. 更新数据(Update)

python 复制代码
update_sql = "UPDATE EMPLOYEE SET age = age + 1 WHERE sex = %s"

with connection.cursor() as cursor:
    cursor.execute(update_sql, ('M',))
    connection.commit()
    print(f"Updated {cursor.rowcount} rows")

5. 删除数据(Delete)

python 复制代码
delete_sql = "DELETE FROM EMPLOYEE WHERE age > %s"

with connection.cursor() as cursor:
    cursor.execute(delete_sql, (25,))
    connection.commit()
    print(f"Deleted {cursor.rowcount} rows")

三、事务管理:确保数据一致性

MySQL 的 InnoDB 引擎支持 ACID 事务。Python 中通过 commit()rollback() 控制:

python 复制代码
try:
    with connection.cursor() as cursor:
        # 转账操作
        cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE user = 'Alice'")
        cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE user = 'Bob'")
    connection.commit()  # 提交事务
except Exception as e:
    connection.rollback()  # 回滚
    print(f"Transaction failed: {e}")

建议 :所有写操作(INSERT/UPDATE/DELETE)必须显式调用 commit() 才会生效!


四、技巧与建议

1. 使用连接池提升性能(生产环境必备)

python 复制代码
from dbutils.pooled_db import PooledDB

pool = PooledDB(
    creator=pymysql,
    maxconnections=10,
    host='localhost',
    user='testuser',
    password='test123',
    database='TESTDB'
)

# 从池中获取连接
conn = pool.connection()
# ... 执行操作 ...
conn.close()  # 归还连接到池

2. 处理异常(Error Handling)

python 复制代码
from pymysql import MySQLError, IntegrityError

try:
    cursor.execute("...")
except IntegrityError as e:
    print("数据完整性错误:", e)
except MySQLError as e:
    print("数据库错误:", e)

3. 批量插入(Bulk Insert)

python 复制代码
data = [
    ('Alice', 'Smith', 30, 'F', 5000.0),
    ('Bob', 'Johnson', 25, 'M', 4500.0)
]

with connection.cursor() as cursor:
    cursor.executemany(insert_sql, data)
    connection.commit()

五、SQLAlchemy(ORM 推荐)

对于复杂项目,建议使用 SQLAlchemy 这样的 ORM(对象关系映射)工具:

python 复制代码
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    first_name = Column(String(50))
    income = Column(Float)

engine = create_engine('mysql+pymysql://user:pwd@localhost/TESTDB')
Session = sessionmaker(bind=engine)
session = Session()

# 添加记录
emp = Employee(first_name='Charlie', income=6000.0)
session.add(emp)
session.commit()

**建议:**避免手写 SQL,代码更面向对象,易于维护。


六、安全与性能

  • 永远使用参数化查询防止 SQL 注入
  • 及时关闭连接避免资源泄漏
  • 使用索引加速查询(尤其 WHERE、JOIN 字段)
  • 避免 SELECT,只取所需字段
  • 敏感信息不要硬编码,使用环境变量或配置文件

小结

掌握 Python 操作 MySQL,是迈向全栈开发或数据工程的重要一步。从基础的 PyMySQL 到高级的 SQLAlchemy,选择适合项目规模的工具,并始终遵循安全、高效、可维护的原则。

"好的数据库代码,不仅跑得快,更要守得住安全底线。"

现在,就去连接你的第一个数据库吧!

相关推荐
databook3 分钟前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田13 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪17 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽17 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战17 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
于眠牧北1 天前
MySQL的锁类型,表锁,行锁,MVCC中所使用的临键锁
mysql
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python