Wednesday, October 31, 2012

MySQLdb does not commit ???? then read this.

If you are newby for python and want to use mysql database with the language. You might have come across this weird behavior at least once in your python time.

Once you check your db after finish running sql query that insert data to your mysql db you might have surprise to see there is no data inserted at all. Actually i had seen something more weird which is first i install MySQLdb package it was ok, it inserted data as it used to be. But after i install mysql c++ headers it start to act weird (for my case, but usually this is how it should happen... you may find in a while )

The problem to not insert the data is that you have not specified it in your connection. In more simpler manner, MySQLdb is not like other database libraries in other language, you have to specifically tell at the beginning to commit your changes automatically or you have to do it manually each time u run an insert sql. Of course yes if you only use your code only to read the data you dont have to do anything at all.

So there are two ways in MySQLdb to commit the data.

First one is to tell the library to commit it after you execute insert sql statements.



con = MySQLdb.Connect(host=host,user=uname,passwd=pwd,db=db)
#your insert sql statements goes here
con.commit()


Next way is to enable auto commit mode at the beginning.



con = MySQLdb.Connect(host=host,user=uname,passwd=pwd,db=db)
con.autocommit(True)
#your insert sql statements goes here


Happy Coding !!!


No comments:

Post a Comment