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 数据库的连接。其中,host、user、password 和 database 分别代表数据库的主机地址、用户名、密码和数据库名称。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。

相关推荐
starzy19901 小时前
Scala循环与判断:一切皆表达式的控制流
开发语言·人工智能·scala
starzy19901 小时前
Scala类和对象:从构造器到样例类的完整指南
开发语言·后端·scala
niucloud-admin1 小时前
NIUCLOUD PHP SAAS上门家政使用文档--服务订单:订单列表
开发语言·php
怪我冷i2 小时前
Rust 的impl语法详解
开发语言·后端·rust
qq_406981032 小时前
c++的decltype是什么
开发语言·c++
坤坤子吖2 小时前
算法学习——单调队列
开发语言·c++·笔记·学习·算法
我就是全世界2 小时前
OpenCode Go 套餐划算吗:先看你用哪个模型
开发语言·后端·golang
螺丝钉tina2 小时前
[Playwright] [02]常用命令与调试:Debug UI、Mode和 Trace Viewer
开发语言·javascript·测试工具·ui·自动化
杜 硕3 小时前
从零开始的C++生活——第六讲——01
开发语言·c++·生活
淡漠的蓝精灵3 小时前
web.py:一个简单到极致的 Python Web 框架
开发语言·前端·python·其他