写一个类,实现MYSQL的多数据库源动态切换,可以快速检测数据库连接
时间: 2023-01-29 19:04:05 浏览: 55
你好!这是一个使用 Python 实现 MySQL 多数据库源动态切换的示例类:
```
import mysql.connector
class MySQLConnectionManager:
def __init__(self, db_configs):
self.db_configs = db_configs
self.cnx = None
self.cursor = None
def __enter__(self):
self.cnx = mysql.connector.connect(**self.db_configs)
self.cursor = self.cnx.cursor()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.cnx.commit()
self.cursor.close()
self.cnx.close()
def switch_database(self, db_name):
self.cursor.execute(f"USE {db_name}")
def execute(self, query, params=None):
self.cursor.execute(query, params)
return self.cursor
```
这个类使用了 Python 中的上下文管理器语法,可以使用 `with` 语句来自动地打开和关闭数据库连接。
你可以使用下面的方式来使用这个类:
```
db_configs = {
"user": "your_username",
"password": "your_password",
"host": "your_host",
"port": 3306,
}
with MySQLConnectionManager(db_configs) as db:
# 执行查询
db.execute("SELECT * FROM users")
# 获取查询结果
result = db.cursor.fetchall()
# 切换数据库
db.switch_database("another_database")
# 执行另一个查询
db.execute("SELECT * FROM orders")
# 获取查询结果
result = db.cursor.fetchall()
```
这个类还提供了一个 `switch_database` 方法,可以在一个打开的连接中动态地切换数据库。
希望这对你有帮助!