pythonpython-db-api

Why does this rollback function not work as expected


I am going to execute 2 sql queries and I want to put them in a transaction, if any query failed then call rollback(). The code is shown as following and 2 queries are

str_trunction: truncate the table & str_insert: insert some rows

codes:

try:
        mydb.start_transaction(consistent_snapshot=False,
                               isolation_level=None,
                               readonly=None)
        mycursor.execute(str_truncate)
        mycursor.executemany(str_insert+'ssss', [data[i].values() for i in range(len(data))])
        raise Exception
        mycursor.commit()

except Exception, e:
        mydb.rollback()
        print("Error captured, rollback. \n %s" % e[0])

finally:
        mycursor.close()
        mydb.close()

As shown, I use +'ssss' to create an exception, when I execute the code, the Exception str Error captured ... is shown as expected, which means the function rollback() should be executed. However, my table is still truncated. Why could this happen?


Solution

  • After try statement add this line

    mydb.autocommit = false