149. Context Managers for Database Connections
1. Basic Context Manager for Database Connections
import sqlite3
class DatabaseConnection:
def __init__(self, db_name):
self.db_name = db_name
self.connection = None
def __enter__(self):
self.connection = sqlite3.connect(self.db_name)
return self.connection
def __exit__(self, exc_type, exc_value, traceback):
if self.connection:
self.connection.close()
# Usage
with DatabaseConnection('example.db') as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM users')
print(cursor.fetchall())Explanation:
2. Using Context Manager with Transactions
Explanation:
3. Using a Context Manager with PostgreSQL
Explanation:
4. Context Manager with Error Handling
Explanation:
5. Context Manager for MongoDB (PyMongo)
Explanation:
6. Context Manager for SQLite with Custom Queries
Explanation:
7. Context Manager for Automatic Database Cleanup
Explanation:
8. Context Manager for Connection Pooling
Explanation:
9. Context Manager for MongoDB Transactions
Explanation:
10. Context Manager for Redis Connections
Last updated