In the lab I mentioned, you need to implement operations against a SQLite database and make sure you aren’t leaving open connections, so you want to open and close the database connections every time. Now, I could just add those 2 lines to every function--it’s not like it’s much--but I’d rather not. So I created the following:
Basically, what I’m doing here is defining a function that takes in another function--it will open the database (which is being assigned to a module level variable), make sure the table we are looking for exists (the only table in the application at this time) and then calls the passed in function. Upon return it will close the database and return what was returned by the other function. Very simple, very clean. An example usage is as follows:
Here all we see is that we run our command to insert the fugitive into the system is merely the SQL statement to do the task (and a logging statement). Easy as pie and everything is open and closed as necessary. We create the function as the parameter into the other function and we get back a function that has been wrapped to automatically open and close the db. Pretty nice huh?
If you’re interested, I’ve got my lab exercise code on git hub and the full DAO can be found here—all with the aforementioned disclaimer that these artifacts are categorically works in progress/trial and error style lab exercises. I’m doing my best to “practice good practices” but learning on my own in a silo leaves some things to be desired—sharing what I am learning and hearing from others is a great way to keep the knowledge flowing. I welcome your feedback!
-Adam Swift, 5AM Solutions
Note: This post appeared originally at Adam's blog, Caffeinated Coding.