MCPcopy Create free account
hub / github.com/ShivaBhattacharjee/KeyZen / DatabaseConnection

Class DatabaseConnection

data/python/08_context_managers.py:1–20  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class DatabaseConnection:
2 def __init__(self, db_name):
3 self.db_name = db_name
4
5 def __enter__(self):
6 print(f"Connecting to database '{self.db_name}'...")
7 self.connected = True
8 return self
9
10 def __exit__(self, exc_type, exc_val, exc_tb):
11 print(f"Closing connection to '{self.db_name}'...")
12 self.connected = False
13 if exc_type:
14 print(f"An error occurred: {exc_val}")
15 return True
16
17 def query(self, sql):
18 if hasattr(self, 'connected') and self.connected:
19 print(f"Executing: {sql}")
20 return [{"id": 1, "data": "Sample"}]
21
22with DatabaseConnection("production_db") as db:
23 results = db.query("SELECT * FROM users")

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected