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

相关推荐
茉莉玫瑰花茶2 小时前
工作流的常见模式 [ 1 ]
java·服务器·前端
_ku_ku_3 小时前
数据库系统原理 · 数据库应用开发 · 自学总结
数据库
No8g攻城狮3 小时前
【人大金仓】wsl2+ubuntu22.04安装人大金仓数据库V9
java·数据库·spring boot·非关系型数据库
山峰哥3 小时前
SQL慢查询调优实战:从全表扫描到索引覆盖的完整复盘
前端·数据库·sql·性能优化
代码中介商4 小时前
Redis入门:5大数据类型全解析
数据库·redis·缓存
渣渣盟4 小时前
数据库设计范式详解(纯小白版)
数据库·oracle·软考·数据库工程师
南京码讯光电技术有限公司5 小时前
工业无线AP选型指南:从WiFi 5到WiFi 6+5G CPE,如何构建全覆盖、零漫游、高可靠的智能工厂网络?
服务器·网络·5g
夜雪闻竹5 小时前
Cursor 对话导入:解析 SQLite 里的宝藏
数据库·sqlite·ai编程
二宝哥6 小时前
Linux虚拟机网络配置
linux·运维·服务器
陳10306 小时前
Linux:进程间通信 和 简单进程池
linux·运维·服务器