title: Context manager for Python's MySQLdb
body: <p>I am used to (spoiled by?) python's <a href="http://docs.python.org/library/sqlite3.html" rel="noreferrer">SQLite</a> interface to deal with SQL databases.  One nice feature in python's SQLite's API  the "context manager," i.e., python's <code>with</code> statement.  I usually execute queries in the following way:</p>
  
  <pre><code>import as sqlite
  
  with sqlite.connect(db_filename) as conn:
      query = "INSERT OR IGNORE INTO shapes VALUES (?,?);"
      results = conn.execute(query, ("ID1","triangle"))
  </code></pre>
  
  <p>With the code above, if my query modifies the database and I forget to run <code>conn.commit()</code>,the context manager runs it for me automatically upon exiting the <code>with</code> statement. It also handles exceptions nicely: if an exception occurs before I commit anything, then the database is rolled back.</p>
  
  <p>I am now using the <code>MySQLdb</code> interface, which doesn't seem to support a similar context manager out of the box.  How do I create my own?  There is a related question <a href="https://stackoverflow.com/questions/1107297/looking-for-a-more-pythonic-way-to-access-the-database">here</a>, but it doesn't offer a complete solution.</p>