Python3 MySQL (PyMySQL) 使用指南

Python3 MySQL (PyMySQL) 使用指南

引言

Python 是一种广泛应用于各种开发场景的编程语言,而 MySQL 则是一款流行的关系型数据库管理系统。PyMySQL 是一个纯 Python 实现的 MySQL 客户端库,它提供了丰富的接口和功能,使得 Python 程序员可以轻松地与 MySQL 数据库进行交互。本文将详细介绍 PyMySQL 的安装、配置和使用方法。

安装 PyMySQL

首先,您需要安装 PyMySQL。可以通过以下命令进行安装:

bash 复制代码
pip install PyMySQL

连接 MySQL 数据库

在使用 PyMySQL 之前,您需要先建立与 MySQL 数据库的连接。以下是一个简单的示例:

python 复制代码
import pymysql

# 连接数据库
connection = pymysql.connect(host='localhost',
                             user='your_username',
                             password='your_password',
                             database='your_database',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # 执行 SQL 查询语句
        sql = "SELECT `user_id`, `user_name` FROM `users`"
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            print(f"User ID: {row['user_id']}, User Name: {row['user_name']}")
finally:
    connection.close()

在上面的代码中,我们首先导入了 pymysql 库,然后创建了一个 pymysql.connect() 对象来建立与 MySQL 数据库的连接。其中,hostuserpassworddatabase 分别代表数据库的主机地址、用户名、密码和数据库名称。charset 参数用于指定连接字符集,cursorclass 参数用于指定游标类型。

执行 SQL 语句

PyMySQL 提供了丰富的接口来执行 SQL 语句。以下是一些常用的 SQL 语句及其对应的 PyMySQL 接口:

  • 查询语句:
python 复制代码
with connection.cursor() as cursor:
    cursor.execute("SELECT * FROM `users`")
    results = cursor.fetchall()
    for row in results:
        print(row)
  • 插入语句:
python 复制代码
with connection.cursor() as cursor:
    cursor.execute("INSERT INTO `users` (`user_name`, `user_age`) VALUES (%s, %s)", ('John Doe', 28))
    connection.commit()
  • 更新语句:
python 复制代码
with connection.cursor() as cursor:
    cursor.execute("UPDATE `users` SET `user_age` = %s WHERE `user_name` = %s", (30, 'John Doe'))
    connection.commit()
  • 删除语句:
python 复制代码
with connection.cursor() as cursor:
    cursor.execute("DELETE FROM `users` WHERE `user_name` = %s", ('John Doe',))
    connection.commit()

使用事务

在执行一系列 SQL 语句时,您可能需要使用事务来确保数据的完整性。以下是如何在 PyMySQL 中使用事务的示例:

python 复制代码
with connection.cursor() as cursor:
    try:
        # 开始事务
        connection.begin()
        
        # 执行多个 SQL 语句
        cursor.execute("INSERT INTO `users` (`user_name`, `user_age`) VALUES (%s, %s)", ('Jane Doe', 25))
        cursor.execute("UPDATE `users` SET `user_age` = %s WHERE `user_name` = %s", (31, 'John Doe'))
        
        # 提交事务
        connection.commit()
    except Exception as e:
        # 回滚事务
        connection.rollback()
        print(f"An error occurred: {e}")

总结

PyMySQL 是一个功能强大的 Python MySQL 客户端库,可以帮助您轻松地与 MySQL 数据库进行交互。本文介绍了 PyMySQL 的安装、配置和使用方法,包括连接数据库、执行 SQL 语句和事务处理等。希望本文能帮助您更好地了解和使用 PyMySQL。

相关推荐
derive_magic1 小时前
wwwwwwjava
开发语言·c#
CoderYanger1 小时前
动态规划算法-简单多状态dp问题:12.打家劫舍Ⅱ
开发语言·算法·leetcode·职场和发展·动态规划·1024程序员节
代数狂人1 小时前
【秒懂C#14 第一章:C#简介】
开发语言·c#
一水鉴天1 小时前
专题讨论 类型理论和范畴理论之间的关系:闭关系/闭类型/闭范畴 与 计算式(ima.copilot)
开发语言·算法·架构
元素之窗1 小时前
MATLAB 的“面子工程”:一键切换数值显示风格 —— format 命令小记
开发语言·算法·matlab
June`1 小时前
C++11新特性全面解析(二):线程库+异常体系
开发语言·c++
上78将1 小时前
什么是Stream流
linux·开发语言·python
洲星河ZXH1 小时前
Java,其他类
java·开发语言