How do I check if an insert was successful with MySQLdb in Python?

bharal picture bharal · Jan 26, 2012 · Viewed 27.5k times · Source

I have this code:

cursor = conn.cursor()
cursor.execute(("insert into new_files (videos_id, filename, "
                "is_processing) values (%s,%s,1)"), (id, filename))
logging.warn("%d", cursor.rowcount)
if (cursor.rowcount == 1):
    logging.info("inserted values %d, %s", id, filename)
else:
    logging.warn("failed to insert values %d, %s", id, filename)
cursor.close()

Fun as it is, cursor.rowcount is always one, even though i updated my database to make the videos_id a unique key. That is, the insert fails because in my tests the same videos_id is going to appear (and when I check the database, nothing was inserted). But for whatever reason, the rowcount is always 1 - even the logging.warn I have spits out a rowcount of 1.

So, the question:
Can I use rowcount to work out if an insert went fine? If so, what am I (presumably) doing wrong? otherwise, how do i check if an insert went fine?

Answer

newtover picture newtover · Jan 26, 2012

Your code does not commit after the modifications (your modifications are rolled back). That is you should add the following line after cursor.execute:

conn.commit()

Failed insert will throw MySQLdb.IntegrityError, so you should be ready to catch it.

Thus, your code should look something like:

sql_insert = """insert into new_files (videos_id, filename, is_processing)
values (%s,%s,1)"""

cursor = conn.cursor()
try:
    affected_count = cursor.execute(sql_insert, (id, filename))
    conn.commit()
    logging.warn("%d", affected_count)
    logging.info("inserted values %d, %s", id, filename)
except MySQLdb.IntegrityError:
    logging.warn("failed to insert values %d, %s", id, filename)
finally:
   cursor.close()