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

相关推荐
会飞的大鱼人1 小时前
一文搞懂 Java HashSet:把它想成游乐园里只允许一次入场的盖章名单
java·开发语言·windows
巨量HTTP1 小时前
Python爬虫动态换IP实战,彻底解决IP403封禁、限流问题(附完整代码)
爬虫·python·tcp/ip·http
jiay21 小时前
【.net10】顶级程序语句
java·开发语言
辰同学ovo1 小时前
从一条 SQL 到三个原则:MySQL 心智模型
sql·mysql·adb
晓子文集2 小时前
Tushare接口文档:指数成分和权重(index_weight)
大数据·数据库·python·金融·量化投资
小大宇2 小时前
python pandas dataFrame sqlAlchemy案例
python·pandas
淼澄研学2 小时前
Python进阶实战:深入解析推导式与生成器等5大核心特性
开发语言·python
xlrqx2 小时前
商丘家电清洗培训零基础学习需掌握哪些要点零基础到底能不能学
python·学习
卷无止境3 小时前
Python虚拟环境江湖:从venv到uv,如何避开依赖冲突的坑
后端·python
玉鸯3 小时前
Agent Harness 工程核心架构拆解与 300 行代码实现
python·agent