在Python中,你可以创建一个MySQL连接类,通常会继承自`mysql-connector-python`库中的`mysql.connector.connection.MySQLConnection`基础类。封装这个类可以帮助管理数据库连接、执行查询以及关闭连接等操作。下面是一个简单的例子:
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`方法负责关闭连接。