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

匆匆过客 提交于 2019-11-29 04:05:39

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()

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.

If the insert fails you'll get a raised exception or someone will yell or you'll fall off your chair.

How about using a try/catch block instead of looking at rowcount. If it catches an exception then there is a problem; otherwise, no problem.

Store the insert statement in the string and print it after. If an exception occurs the statement won't print.

sql_insert = """insert into new_files (videos_id, filename, is_processing)
values (%s,%s,1)"""
cur.execute(sql_insert)
print('Executed:', sql_insert)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!