如何检查Python中MySQLdb的插入是否成功? [英] How do I check if an insert was successful with MySQLdb in Python?

查看:178
本文介绍了如何检查Python中MySQLdb的插入是否成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

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

很有趣,即使我更新了数据库以使videos_id成为唯一键,cursor.rowcount也总是 .也就是说,插入失败,因为在我的测试中将出现相同的videos_id(并且当我检查数据库时,未插入任何内容). 但是无论出于什么原因,rowcount始终为1-甚至我已经将logging.warn吐出的rowcount都为1.

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.

所以,问题是:
如果插入效果良好,我可以使用rowcount进行计算吗?如果是这样,我(大概)在做错什么? 否则,我该如何检查插入片段是否正常?

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?

推荐答案

修改后(您的修改会回滚),您的代码不会提交.也就是说,您应该在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()

这篇关于如何检查Python中MySQLdb的插入是否成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆