Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 376
bharal Avatar asked Jan 26 '12 05:01

bharal


2 Answers

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()
like image 151
newtover Avatar answered Oct 11 '22 15:10

newtover


I don't have enough reputation to make a comment, but here's an important note:

It is also possible for execute() to fail silently if you don't commit after the call. Namely, MyISAM tables don't require the commit, but InnoDB ones do.

like image 36
TApicella Avatar answered Oct 11 '22 15:10

TApicella