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,选择适合项目规模的工具,并始终遵循安全、高效、可维护的原则。

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

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

相关推荐
阿钱真强道7 小时前
13 JetLinks MQTT:网关设备与网关子设备 - 温控设备场景
python·网络协议·harmonyos
我的xiaodoujiao7 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 47--设置Selenium以无头模式运行代码
python·学习·selenium·测试工具·pytest
傻乐u兔8 小时前
C语言进阶————指针4
c语言·开发语言
大模型玩家七七8 小时前
基于语义切分 vs 基于结构切分的实际差异
java·开发语言·数据库·安全·batch
历程里程碑8 小时前
Linux22 文件系统
linux·运维·c语言·开发语言·数据结构·c++·算法
牛奔9 小时前
Go 如何避免频繁抢占?
开发语言·后端·golang
寻星探路13 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly20240615 小时前
Bootstrap 警告框
开发语言
2601_9491465315 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言