且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查Python中MySQLdb的插入是否成功?

更新时间:2023-11-26 09:06:04

修改后(您的修改会回滚),您的代码不会提交.也就是说,您应该在cursor.execute之后添加以下行:

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

插入失败将抛出MySQLdb.IntegrityError,因此您应该准备好抓住它.

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