python封装一个 MySQL 的连接器,支持 open/close

发布于:2024-08-14 ⋅ 阅读:(142) ⋅ 点赞:(0)

在Python中,封装一个MySQL连接器通常涉及创建一个类,该类负责维护数据库连接的状态,并提供易于使用的open()和close()方法。以下是一个简单的例子,展示了如何使用`pymysql`库封装MySQL连接:
 

import pymysql

class MySQLConnector:
    def __init__(self, host, user, password, db):
        self.host = host
        self.user = user
        self.password = password
        self.db = db
        self.conn = None

    def open_connection(self):
        try:
            self.conn = pymysql.connect(host=self.host,
                                        user=self.user,
                                        password=self.password,
                                        database=self.db)
            print("Connected to MySQL successfully.")
        except pymysql.Error as e:
            print(f"Error connecting to MySQL: {e}")

    def close_connection(self):
        if self.conn is not None:
            self.conn.close()
            print("Connection closed.")
        else:
            print("Connection was already closed.")

# 使用示例
connector = MySQLConnector('localhost', 'your_username', 'your_password', 'your_database')
connector.open_connection()  # 这里会尝试建立连接
# ... 进行操作 ...
connector.close_connection()  # 当不再需要连接时关闭

在这个封装中,`__init__`方法初始化了连接的属性,而`open_connection()`方法用于打开连接,如果连接失败则显示错误消息。同样,`close_connection()`方法检查是否有连接,如果有,则关闭它并打印一条消息。