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' 需要替换为实际的数据库登录信息和表名。

相关推荐
张洛闻Eren3 小时前
MySQL 维护稳定系统【MySQL第二课】
linux·数据库·mysql·云原生
布莱克6054 小时前
理解索引:从概念到实践
数据库·mysql
fiveym5 小时前
01 - iPXE + Clonezilla 网络装机原理解析
linux·运维·服务器·网络
虎头金猫5 小时前
如何在群晖NAS上通过Docker部署CloudSaver?群晖部署CloudSaver教程|聚合资源搜索并实现远程访问
运维·服务器·网络·python·docker·容器·pandas
dog2505 小时前
网络优化,还是降低各阶矩
服务器·网络·php
我不是疯子是傻子8 小时前
Qt CAN通信周期发送抖动?实测定时器精度校准与时间戳补偿方案
开发语言·数据库·qt
这个DBA有点耶8 小时前
数据库迁移怎么做到“零翻车“:金仓 KDMS/KDTS/KFS 工具链实测
数据库·架构·dba
2501_937860949 小时前
MySQL联合查询(多表查询)
数据库·mysql
非凡ghost9 小时前
分区助手:Windows 磁盘管理的“瑞士军刀“,分区调整不再怕丢数据
服务器·windows·电脑·软件需求
名字还没想好☜9 小时前
Next.js 用 Server Components 直连数据库:去掉 API 层的边界,和三条别踩的安全红线
前端·javascript·数据库·安全·react·next.js