A context manager: Create a context manager that handles the connection and cursor creation, as well as closing the connection when done. This way, you can use the with statement to manage the connection and cursor in your functions.
This, but, with DatabaseConnection being a singleton, and preventing multiple enter clauses.
You can ensure it's a singleton by modifying how a new object is built, by overriding the new dunder method. If an instance exists, return that, otherwise create a new one.
I've always liked SQL, so I avoided ORMs for a long time... They are great for so many reasons! I definitely recommend you ORMs, specially the ones that also help you with migrations.
A context manager: Create a context manager that handles the connection and cursor creation, as well as closing the connection when done. This way, you can use the
withstatement to manage the connection and cursor in your functions.This, but, with DatabaseConnection being a singleton, and preventing multiple enter clauses.
You can ensure it's a singleton by modifying how a new object is built, by overriding the new dunder method. If an instance exists, return that, otherwise create a new one.
A function decorator: You can create a decorator that handles the connection and cursor creation and passes the cursor to the decorated function.
Have you thought about using an ORM?
I've always liked SQL, so I avoided ORMs for a long time... They are great for so many reasons! I definitely recommend you ORMs, specially the ones that also help you with migrations.