149. Context Managers for Database Connections
Here are 10 Python code snippets demonstrating how to use context managers to manage database connections. These examples will help you manage resources (like database connections) more efficiently by ensuring that connections are properly opened and closed, even when exceptions occur.
1. Basic Context Manager for Database Connections
This snippet creates a basic context manager for managing a database connection.
Copy
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:
__enter__: Establishes the connection.__exit__: Ensures that the connection is closed after the block of code is executed.
2. Using Context Manager with Transactions
Automatically managing transactions in a database connection.
Copy
Explanation:
The context manager handles committing the transaction unless there is an exception, in which case it rolls back.
3. Using a Context Manager with PostgreSQL
Managing a PostgreSQL database connection using the psycopg2 library.
Copy
Explanation:
This example uses
psycopg2for PostgreSQL, and the context manager handles connection opening and closing automatically.
4. Context Manager with Error Handling
Automatically handling exceptions when interacting with the database.
Copy
Explanation:
This context manager ensures that errors are logged, and the connection is rolled back if there is a problem with the query.
5. Context Manager for MongoDB (PyMongo)
Managing a MongoDB connection using a custom context manager.
Copy
Explanation:
This example uses
PyMongofor MongoDB connections, ensuring that the connection is automatically closed after use.
6. Context Manager for SQLite with Custom Queries
Using a context manager to execute queries in a SQLite database.
Copy
Explanation:
This context manager allows for executing queries and ensures the connection is properly closed.
7. Context Manager for Automatic Database Cleanup
Automatically cleaning up database tables after use.
Copy
Explanation:
This context manager cleans up temporary data in the database, ensuring that no leftover data remains.
8. Context Manager for Connection Pooling
Using connection pooling in a database connection manager.
Copy
Explanation:
This example demonstrates how to use connection pooling to manage connections to the database.
9. Context Manager for MongoDB Transactions
Using a context manager to handle MongoDB transactions.
Copy
Explanation:
This example uses
PyMongofor MongoDB transactions with a context manager.
10. Context Manager for Redis Connections
Managing Redis connections with a custom context manager.
Copy
Last updated