Context manager support with connection object #947
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Is your feature request related to a problem? Please describe.
When working with IO, It is common to acquire some resource i.e open('file.txt') or ibm_db_dbi.connect(connection_str). These resources also have to manually closed i.e fp.close() or connection.close(). Developers may forget to clean up this resources and this could lead to resource leaks. Python solves this problem with context managers which automatically solve the problem of resource management and ensure proper cleanup. They provide a convenient and reliable way to allocate and release resources, such as connecting and disconnecting from a database.
Context managers could provide a concise and intuitive way to handle database connections and transactions, ensuring proper cleanup and reducing the risk of resource leaks. With context managers, developers can write cleaner and more readable code by encapsulating the database-related operations within a well-defined scope. Additionally, context managers can also enable automatic rollback of transactions in case of exceptions, ensuring data consistency and integrity.
Describe the solution you'd like
Context managers to be added to connection objects such that they can be used easily like:
with ibm_db_dbi.connect(connection_str) as connection:
cursor = connection.cursor()
cursor.execute('SELECT * from table')
result = cursor.fetchall()
This removes the need for manual cleanup of resources
Describe alternatives you've considered
Additional context