Python pymysql 操作 MySQL 详细指南

叶初
叶初
发布时间:2026-10-14| 2人浏览过
原创

本文详细介绍如何使用Python的pymysql库连接MySQL数据库。内容涵盖基础连接配置、处理中文乱码的关键参数charset,以及获取单条和多条结果的方法。此外,文章提供了将数据库操作封装为工具类的代码示例,包括连接创建、执行SQL语句及资源释放的完整流程,帮助开发者高效进行数据库交互。

1、使用

1.1 简单使用


import pymysql

# 创建连接
con = pymysql.connect(
                        host='localhost',
                        port=3306,
                        user='root',
                        password='123456',
                        database='test',
                        charset='utf8'
)
# 创建游标
cursor = con.cursor()

# 执行新增SQL,返回受影响行数
row1 = cursor.execute("insert into user (username, password) values ('username3','password3')")
print(row1)

# 执行更新SQL,返回受影响行数
row2 = cursor.execute("update user set password = '123456' where id > 2;")
# 执行查询SQL
res = cursor.execute("SELECT * FROM user;")
result = cursor.fetchall()
for info in result:
    print(info[0], info[1])
# 提交,不然无法保存新增或者更新的数据
con.commit()
# 关闭游标
cursor.close()
# 关闭连接
con.close()

注意:当数据库表中包含中文字符时,在建立数据库连接时必须指定charset='utf8'参数,否则读取或显示中文时会出现乱码现象。其中,cursor.fetchall()用于获取查询返回的所有结果集;如果预期只有一条结果,可以使用cursor.fetchone()来直接获取该条记录。

1.2 封装工具类

为了提升代码复用性和使用便捷性,可以将数据库操作封装为一个通用的工具类:


import pymysql


class MysqlHelper:
    def __init__(self, config):
        self.host = config["host"]
        self.port = config["port"]
        self.user = config["user"]
        self.password = config["password"]
        self.db = config["db"]
        self.charset = config["charset"]
        self.con = None
        self.cursor = None

    def create_con(self):
        """
        创建连接
        """
        try:
            self.con = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password,
                                       database=self.db, charset='utf8')
            self.cursor = self.con.cursor()
            return True
        except Exception as e:
            print(e)
            return False

    #
    def close_con(self):
        """
        关闭链接
        """
        if self.cursor:
            self.cursor.close()
        if self.con:
            self.con.close()

    # sql执行
    def execute_sql(self, sql):
        """
        执行插入/更新/删除语句
        """
        try:
            self.create_con()
            print(sql)
            self.cursor.execute(sql)
            self.con.commit()
        except Exception as e:
            print(e)
        finally:
            self.close_con()

    def select(self, sql, *args):
        """
        执行查询语句
        """
        try:
            self.create_con()
            print(sql)
            self.cursor.execute(sql, args)
            res = self.cursor.fetchall()
            return res
        except Exception as e:
            print(e)
            return False
        finally:
            self.close_con()

使用该工具类的示例代码如下:


config = {
    "host": 'localhost',
    "port": 3306,
    "user": 'root',
    "password": '123456',
    "db": 'test',
    "charset": 'utf8'
}
db = MysqlHelper(config)
db.execute_sql("insert into user (username, password) values ('username4','password4')")
db.select("SELECT * FROM user;")

至此,关于Python pymysql操作MySQL的详细教程介绍完毕。如需了解更多相关Python pymysql操作MySQL的内容,建议搜索本站历史文章或继续阅读后续相关文章,感谢大家的支持!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。