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

相关推荐
aqi001 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn2 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵18 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent