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

相关推荐
Flittly8 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling12 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook15 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风16 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风17 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
0xDevNull1 天前
MySQL索引进阶用法
后端·mysql
0xDevNull1 天前
MySQL索引用法
mysql
zone77392 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试