创建一个Database接口,包含connect()方法和disconnect()方法,用于连接和断开数据库连接。然后创建一个MySQLDatabase类和一个OracleDatabase类,它们都实现了Database接口,并分别实现了连接和断开连接的方法。
时间: 2024-03-21 15:39:51 浏览: 43
数据库连接方法包括连接和关闭资源
5星 · 资源好评率100%
好的,以下是实现代码:
```python
from abc import ABC, abstractmethod
class Database(ABC):
@abstractmethod
def connect(self):
pass
@abstractmethod
def disconnect(self):
pass
class MySQLDatabase(Database):
def __init__(self, host, username, password, database):
self.host = host
self.username = username
self.password = password
self.database = database
def connect(self):
print(f"Connecting to MySQL database {self.database} at {self.host} as {self.username}...")
# 连接MySQL数据库的代码
print("Connected to MySQL database.")
def disconnect(self):
print(f"Disconnecting from MySQL database {self.database} at {self.host}...")
# 断开MySQL数据库连接的代码
print("Disconnected from MySQL database.")
class OracleDatabase(Database):
def __init__(self, host, username, password, database):
self.host = host
self.username = username
self.password = password
self.database = database
def connect(self):
print(f"Connecting to Oracle database {self.database} at {self.host} as {self.username}...")
# 连接Oracle数据库的代码
print("Connected to Oracle database.")
def disconnect(self):
print(f"Disconnecting from Oracle database {self.database} at {self.host}...")
# 断开Oracle数据库连接的代码
print("Disconnected from Oracle database.")
```
以上是一个基本的实现,你可以根据自己的需求对其进行扩展和修改。
阅读全文