一、环境准备
-
安装 MySQL 数据库:确保本地或服务器已安装并启动 MySQL 服务。
-
安装 Python MySQL 驱动库:常用库有 pymysql(纯 Python 实现,推荐)和 mysql-connector-python(官方驱动)。
二、连接数据库 使用 pymysql.connect() 建立与 MySQL 的连接,需提供数据库地址、用户名、密码、数据库名等参数。
import pymysql
建立数据库连接
try:
connection = pymysql.connect(
host='localhost', # 数据库地址
user='root', # 用户名
password='your_password',# 密码
database='test_db', # 数据库名
port=3306, # 端口(默认3306)
charset='utf8mb4' # 字符集
)
print("数据库连接成功!")
except pymysql.MySQLError as e:
print(f"连接失败:{e}")
三、执行 SQL 操作 通过 cursor() 创建游标对象,使用 execute() 执行 SQL 语句。
1. 创建表
try:
with connection.cursor() as cursor:
编写 SQL 语句
create_table_sql = """
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT,
email VARCHAR(100) UNIQUE
)
"""
cursor.execute(create_table_sql)
connection.commit() # 提交事务
print("表创建成功!")
except pymysql.MySQLError as e:
connection.rollback() # 出错回滚
print(f"创建表失败:{e}")
2. 插入数据 • 单条插入:
try:
with connection.cursor() as cursor:
insert_sql = "INSERT INTO users (name, age, email) VALUES (%s, %s, %s)"
cursor.execute(insert_sql, ('张三', 25, 'zhangsan@example.com'))
connection.commit()
print(f"插入成功,影响行数:{cursor.rowcount}")
except pymysql.MySQLError as e:
connection.rollback()
print(f"插入失败:{e}")
• 批量插入: python 运行 try:
with connection.cursor() as cursor:
insert_sql = "INSERT INTO users (name, age, email) VALUES (%s, %s, %s)"
users_data = [
('李四', 30, 'lisi@example.com'),
('王五', 28, 'wangwu@example.com')
]
cursor.executemany(insert_sql, users_data) # 批量执行
connection.commit()
print(f"批量插入成功,影响行数:{cursor.rowcount}")
except pymysql.MySQLError as e:
connection.rollback()
print(f"批量插入失败:{e}")
3. 查询数据 使用 fetchone()(获取单条)、fetchall()(获取所有)或 fetchmany(n)(获取 n 条)获取结果。
try:
with connection.cursor() as cursor:
query_sql = "SELECT * FROM users WHERE age > %s"
cursor.execute(query_sql, (25,))
获取所有结果
results = cursor.fetchall()
print("查询结果:")
for row in results:
print(f"ID: {row[0]}, 姓名: {row[1]}, 年龄: {row[2]}, 邮箱: {row[3]}")
except pymysql.MySQLError as e:
print(f"查询失败:{e}")
4. 更新数据
try:
with connection.cursor() as cursor:
update_sql = "UPDATE users SET age = %s WHERE name = %s"
cursor.execute(update_sql, (26, '张三'))
connection.commit()
print(f"更新成功,影响行数:{cursor.rowcount}")
except pymysql.MySQLError as e:
connection.rollback()
print(f"更新失败:{e}")
5. 删除数据
try:
with connection.cursor() as cursor:
delete_sql = "DELETE FROM users WHERE name = %s"
cursor.execute(delete_sql, ('王五',))
connection.commit()
print(f"删除成功,影响行数:{cursor.rowcount}")
except pymysql.MySQLError as e:
connection.rollback()
print(f"删除失败:{e}")
四、关闭连接 操作完成后,需关闭游标和数据库连接:
if connection:
connection.close()
print("数据库连接已关闭")
五、注意事项
-
事务管理:增删改操作需 commit() 提交,出错时用 rollback() 回滚。
-
SQL 注入防护:使用 %s 占位符传递参数,避免字符串拼接 SQL。
-
资源释放:使用 with 上下文管理器可自动关闭游标,简化代码。