安装 PyMySQL
PyMySQL 是一个纯 Python 实现的 MySQL 客户端库,支持 Python 3.x。安装 PyMySQL 可以通过 pip 命令完成:
pip install pymysql
连接 MySQL 数据库
使用 PyMySQL 连接 MySQL 数据库需要提供主机地址、用户名、密码、数据库名等信息:
import pymysql
# 建立数据库连接
connection = pymysql.connect(
host='localhost',
user='username',
password='password',
database='db_name',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
host
:MySQL 服务器地址,本地为localhost
。user
和password
:数据库登录凭据。database
:连接的数据库名称。charset
:设置字符集,推荐使用utf8mb4
以支持完整 Unicode。cursorclass
:指定游标类型,DictCursor
返回字典形式的结果。
创建游标并执行 SQL
游标用于执行 SQL 语句并获取结果:
try:
# 构建一个游标对象,用于与数据库交互
cursor = connection.cursor()
cursor.execute("show databases")
# 获取所有结果
rows = cursor.fetchall()
print(rows)
for row in rows:
print(row)
# 提交事务(INSERT/UPDATE/DELETE 需要)
connection.commit()
finally:
# 关闭游标
cursor.close()
# 关闭数据库连接
connection.close()
cursor.execute(sql, args)
:执行 SQL 语句,args
为参数化查询的参数。fetchone()
:获取一条结果。fetchall()
:获取所有结果。commit()
:提交事务,确保数据修改生效。
插入数据
插入数据使用 INSERT
语句,并通过参数化查询防止 SQL 注入:
with connection.cursor() as cursor:
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
cursor.execute(sql, ('Alice', 'alice@example.com'))
connection.commit()
更新数据
更新数据使用 UPDATE
语句:
with connection.cursor() as cursor:
sql = "UPDATE users SET email = %s WHERE name = %s"
cursor.execute(sql, ('new_email@example.com', 'Alice'))
connection.commit()
删除数据
删除数据使用 DELETE
语句:
with connection.cursor() as cursor:
sql = "DELETE FROM users WHERE name = %s"
cursor.execute(sql, ('Alice',))
connection.commit()
错误处理
数据库操作可能出现异常,建议使用 try-except
捕获错误:
try:
with connection.cursor() as cursor:
sql = "SELECT * FROM non_existent_table"
cursor.execute(sql)
except pymysql.Error as e:
print(f"Database error: {e}")
finally:
connection.close()
使用上下文管理器
Python 的 with
语句可以简化连接管理:
with pymysql.connect(
host='localhost',
user='username',
password='password',
database='db_name'
) as connection:
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
print(result)
批量插入
使用 executemany()
可以高效插入多条数据:
data = [('Bob', 'bob@example.com'), ('Charlie', 'charlie@example.com')]
with connection.cursor() as cursor:
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
cursor.executemany(sql, data)
connection.commit()