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`方法负责关闭连接。

相关推荐
金銀銅鐵18 小时前
[Python] 扩展欧几里得算法
python·数学·算法
Duckdblab19 小时前
DuckDB 性能调优终极指南:打造闪电般的分析体验
python
带派擂总19 小时前
Python全栈开发精华版最全合集(包含各种面试题) Day24_异常和错误
python
元Y亨H1 天前
技术笔记:MySQL 字符集排序规则与大小写敏感性问题解决方案
mysql
金銀銅鐵1 天前
n^5 和 n 的个位数是否总相等?
python·数学
aqi001 天前
15天学会AI应用开发(九)利用Chroma持久化向量数据
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
借助 Pygame 探索最大公约数的规律
python·数学·游戏
ServBay2 天前
9 个 Python 第三方库推荐,不用 AI 都好像多出一个团队
后端·python
用户8356290780512 天前
如何使用 Python 添加和管理 Excel 批注(完整示例)
后端·python