db.commit() to take effect

Maurice LING mauriceling at acm.org
Sun Dec 3 01:53:51 EST 2006


John Machin wrote:
> progman wrote:
> 
>>I was testing the python+mysql
>>
>>here are my sample codes:
>>------------------------
>>import MySQLdb
>>from pprint import pprint
>>db = MySQLdb.connect(host="localhost", user="root", passwd="password",
>>db="database")
>>cursor = db.cursor()
>>cursor.execute('update promo set date=100")
>>
>>
>>------------------------
>>
>>i was expecting the cursor.execute will update my db immediately.
>>it wasn't. not until i  run db.commit(), then only i see the value
>>changes.
>>
>>it that the right way to update db?
> 
> 
> Short answer: yes
> 
> Longer answer: In most non-trivial db apps, to carry out a given
> real-world transaction, you will need to do multiple updates/inserts,
> and you want them all to happen, or none to happen. The database would
> be inconsistent if your app or server crashed half-way through. Imagine
> you are transferring some money to someone else's bank account. The
> money gets deducted from your account but not added to theirs -- not
> good. [A real banking system would not be that simple, but you should
> get the general idea.]  So you do db.commit() after the last
> insert/update.
> 
> HTH,
> John
> 

Adding to that, PEP 249 specified that if a DBMS has auto-commit 
feature, it should be set to "off", implying that cursor.execute() and 
cursor.executemany() methods do not commit the database. Database commit 
is defined as .commit() method in connect object.

Cheers
ML



More information about the Python-list mailing list