PyMySQL库的使用方法

过程和步骤:

安装 PyMySQL

首先,需要使用 pip 安装 PyMySQL 库:

bash 复制代码
pip install pymysql

连接数据库

使用 PyMySQL.connect() 方法可以建立到 MySQL 数据库的连接:

python 复制代码
import pymysql

# 配置数据库连接参数
config = {
    'host': 'localhost',     # 数据库服务器地址
    'port': 3306,            # 数据库服务器端口
    'user': 'your_username', # 数据库用户名
    'password': 'your_password', # 数据库密码
    'database': 'your_database', # 要操作的数据库名
    'charset': 'utf8mb4'     # 使用的字符集
}

# 建立连接
connection = pymysql.connect(**config)

创建游标对象

游标(Cursor)用于执行 SQL 语句和获取查询结果:

python 复制代码
# 创建游标对象
cursor = connection.cursor()

执行 SQL 语句

使用游标的 execute() 方法可以执行 SQL 语句:

python 复制代码
# 执行查询语句
cursor.execute("SELECT * FROM your_table")

# 获取所有查询结果
results = cursor.fetchall()
for row in results:
    print(row)

# 执行非查询语句(如 INSERT、UPDATE、DELETE)
cursor.execute("INSERT INTO your_table (column1, column2) VALUES (value1, value2)")

提交事务

对于非查询类的 SQL 语句,需要提交事务以确保更改生效:

python 复制代码
connection.commit()

错误处理

使用 try...except 语句来处理可能发生的异常:

python 复制代码
try:
    # 尝试执行一些操作
    pass
except pymysql.MySQLError as e:
    print(e)
    connection.rollback()  # 发生错误时回滚事务
finally:
    cursor.close()  # 关闭游标
    connection.close()  # 关闭连接

关闭连接

操作完成后,应关闭游标和数据库连接:

python 复制代码
cursor.close()
connection.close()

示例代码

下面是一个使用 PyMySQL 执行查询和插入操作的完整示例:

python 复制代码
import pymysql

# 配置数据库连接参数
config = {
    'host': 'localhost',
    'port': 3306,
    'user': 'your_username',
    'password': 'your_password',
    'database': 'your_database',
    'charset': 'utf8mb4'
}

# 建立连接
connection = pymysql.connect(**config)

try:
    # 创建游标对象
    with connection.cursor() as cursor:
        # 执行查询
        cursor.execute("SELECT * FROM your_table")
        print("Query results:", cursor.fetchall())

        # 执行插入操作
        cursor.execute("INSERT INTO your_table (column1, column2) VALUES (%s, %s)", ('value1', 'value2'))

    # 提交事务
    connection.commit()

except pymysql.MySQLError as e:
    print("Error: ", e)
    connection.rollback()
finally:
    # 关闭连接
    connection.close()

请注意,上述示例中的 'your_username', 'your_password', 'your_database''your_table' 需要替换为实际的数据库登录信息和表名。

相关推荐
一 乐10 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
1.14(java)12 小时前
SQL数据库操作:从CRUD到高级查询
数据库
Full Stack Developme12 小时前
数据库索引的原理及类型和应用场景
数据库
cuijiecheng201813 小时前
Linux下Beyond Compare过期
linux·运维·服务器
期待のcode13 小时前
前后端分离项目 Springboot+vue 在云服务器上的部署
服务器·vue.js·spring boot
AI 智能服务13 小时前
第6课__本地工具调用(文件操作)
服务器·人工智能·windows·php
IDC02_FEIYA14 小时前
SQL Server 2025数据库安装图文教程(附SQL Server2025数据库下载安装包)
数据库·windows
辞砚技术录14 小时前
MySQL面试题——联合索引
数据库·面试
萧曵 丶15 小时前
MySQL 主键不推荐使用 UUID 的深层原因
数据库·mysql·索引
小北方城市网15 小时前
分布式锁实战指南:从选型到落地,避开 90% 的坑
java·数据库·redis·分布式·python·缓存