Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database does not update automatically with MySQL and Python

I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:

import MySQLdb

conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname")
cursor=conn.cursor()

cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100")
cursor.execute("SELECT Co_num FROM compinfo WHERE ID=100")
results = cursor.fetchall()

for row in results:
    print row[0]

print "Number of rows updated: %d" % cursor.rowcount

cursor.close()
conn.close()

The output I get when I run this program is:

4
Number of rows updated: 1

It seems like it's working but if I query the database from the MySQL command line interface (CLI) I find that it was not updated at all. However, if from the CLI I enter UPDATE compinfo SET Co_num=4 WHERE ID=100; the database is updated as expected.

What is my problem? I'm running Python 2.5.2 with MySQL 5.1.30 on a Windows box.

like image 912
Ian Burris Avatar asked Dec 21 '08 07:12

Ian Burris


People also ask

Does MySQL update automatically?

Any server with a local installation of MySQL 5.5 and no databases will automatically update to MySQL 5.7 or newer.

Is Python compatible with MySQL?

MySQL server and Python versions within parentheses are known to work with Connector/Python, but are not officially supported. Bugs might not get fixed for those versions. Connector/Python does not support the old MySQL Server authentication methods, which means that MySQL versions prior to 4.1 will not work.


2 Answers

I am not certain, but I am going to guess you are using a INNODB table, and you haven't done a commit. I believe MySQLdb enable transactions automatically.

Call conn.commit() before calling close.

From the FAQ: Starting with 1.2.0, MySQLdb disables autocommit by default

like image 196
Zoredache Avatar answered Oct 25 '22 22:10

Zoredache


MySQLdb has autocommit off by default, which may be confusing at first. Your connection exists in its own transaction and you will not be able to see the changes you make from other connections until you commit that transaction.

You can either do conn.commit() after the update statement as others have pointed out, or disable this functionality altogether by setting conn.autocommit(True) right after you create the connection object.

like image 32
ʞɔıu Avatar answered Oct 25 '22 21:10

ʞɔıu