MySQLdb - when to commit and execute?
<p>I'm using MySQLdb in Python 2, and I have a question about executing queries into the database. Say I have some connection <code>con</code>, and I instantiate a cursor with <code>cur = con.cursor()</code>. Which of the following is the proper way to commit changes to the database? Bonus points if you could explain the theory behind the correct answer :)</p>

<p>Method 1:</p>

<pre><code>try:
    cur.execute('command 1')
    con.commit()
    cur.execute('command 2')
    con.commit()
except MySQLdb.Error as e:
    con.rollback()
</code></pre>

<p>Method 2:</p>

<pre><code>try:
    cur.execute('command 1')
    cur.execute('command 2')
    con.commit()
except MySQLdb.Error as e:
    con.rollback()
</code></pre>

<p>Method 3:</p>

<pre><code>try:
    cur.execute('command 1')
    try:
        cur.execute('command 2')
    except MySQLdb.Error as e:
        con.rollback()
    con.commit()
except MySQLdb.Error as e:
    con.rollback()
</code></pre>