On Fri, Aug 8, 2014 at 5:13 PM, Chris Angelico <ros...@gmail.com> wrote:
> On Sat, Aug 9, 2014 at 9:55 AM, Chris Kaynor <ckay...@zindagigames.com> > wrote: > > try: > > action > > commit > > finally: > > rollback > > If commit/rollback automatically opens a new transaction, this would > just roll back an empty transaction - not a big deal. But yes, I do > see what you're looking at here. > > However, structures like this are necessary only if you're hanging > onto the database connection. Python gives you a well-defined > unhandled-exception handler, and it's easy to just let exceptions > happen - if something goes wrong, you won't commit, and you'll get a > helpful traceback on the console. My recommended model for Python > databasing is: > > Create database connection, get cursor > while "work to do": > do work > Commit > > Until such time as you have a demonstrable need for more complexity, > this model is safe, simple, and easy to work with. And less code > generally means less bugs :) > The main issue I can see with that idea is that the exception will keep a reference to the database connection (as with all locals), so unless you explicitly close it within a finally clause, the database connection could still be left hanging, and thus no rollback will occur. With just: openConnection while workToDo: doWork commit If at any time, doWork throws an exception, the connection could be left hanging, especially if the code is being run as an interactive script, and not as an application. I believe this is one case where explicit is better than implicit :) - its better to explicitly free the external resources, at the minimum, with something like: openConnection try: while worktoDo: doWork commit finally: closeConnection But, depending on the needs of the system (longer living connections, for example), that may need to have explicit rollback as well. As a rule of thumb, I have a context manger to deal with the specific needs (either just a "with transition" or a "with connection"). Keeps the code cleaner :). Chris
-- https://mail.python.org/mailman/listinfo/python-list