python封装一个 MySQL 连接类,继承自 MySQLConnector

在Python中,你可以创建一个MySQL连接类,通常会继承自`mysql-connector-python`库中的`mysql.connector.connection.MySQLConnection`基础类。封装这个类可以帮助管理数据库连接、执行查询以及关闭连接等操作。下面是一个简单的例子:

python 复制代码
import mysql.connector

class MysqlDBConnection(mysql.connector.Connection):
    def __init__(self, host='localhost', user='username', password='password', database='dbname'):
        super().__init__()
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connect()

    def connect(self):
        try:
            self.connect(host=self.host, user=self.user, password=self.password, database=self.database)
            print("Connected to MySQL")
        except mysql.connector.Error as err:
            print(f"Error connecting to MySQL: {err}")

    def execute_query(self, query):
        cursor = self.cursor()
        try:
            cursor.execute(query)
            result = cursor.fetchall()
            return result
        finally:
            cursor.close()

    def close(self):
        if self.is_connected():
            self.close()
            print("MySQL connection closed.")

# 使用示例
conn = MysqlDBConnection()
result = conn.execute_query("SELECT * FROM table_name")
conn.close()

在这个例子中,`MysqlDBConnection`类初始化时连接到数据库,并提供了一些额外的方法如`execute_query`用于执行SQL查询,以及`close`方法负责关闭连接。

相关推荐
Yang96112 分钟前
0.5 米超短盲区!鼎讯信通 GO-50PRO 光时域反射仪科普
开发语言·后端·golang
不会C语言的男孩7 分钟前
C++ Primer Plus 第12章:类和动态内存分配
开发语言·c++
To_OC11 分钟前
Python 字典和集合,原来底层是这么玩的
python
骄马之死13 分钟前
缓存与数据库一致性的核心方案
mysql·缓存
星卯教育tony19 分钟前
CIE中国电子学会2026年3月c++ Python scratch 机器人真题试卷含参考答案
c++·python·scratch·电子学会
阿里嘎多学长29 分钟前
2026-05-30 GitHub 热点项目精选
开发语言·程序员·github·代码托管
linksinke29 分钟前
在 CentOS 7.x 外网环境离线构建便携式 Python 3.11.4 的方案参考
linux·python·centos
wapicn9931 分钟前
API接口调试笔记:从注册到第一个数据返回,全流程详解
java·开发语言·python·lua
logo_2832 分钟前
python指定目录进行虚拟环境配置
python·虚拟环境
大数据魔法师35 分钟前
Streamlit(十七)- API 参考文档(十)- 身份认证与用户信息组件
python·web