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

相关推荐
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger1 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥2 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud2 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术2 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
christine-rr2 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
可涵不会debug2 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom2 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试