Python MySQLdb/MySQL INSERT IGNORE&检查是否被忽略 [英] Python MySQLdb / MySQL INSERT IGNORE & Checking if Ignored
问题描述
我知道,检查行是否存在的最快方法甚至不是检查,而是在插入新数据时使用INSERT IGNORE.这对于我的应用程序来说是最出色的.但是,我需要能够检查插入是否被忽略(或者相反,是否实际插入了行).
I understand that the fastest way to check if a row exists isn't even to check, but to use an INSERT IGNORE when inserting new data. This is most excellent for my application. However, I need to be able to check if the insert was ignored (or conversely, if the row was actually inserted).
我可以使用try/catch,但这不是很优雅.希望有人可能有一个更清洁,更优雅的解决方案.
I could use a try/catch, but that's not very elegant. Was hoping that someone might have a cleaner and more elegant solution.
推荐答案
自然地,我发布问题后的最终搜索会产生结果.
Naturally, a final search after I post the question yields the result.
但是,这仍然需要第二次访问数据库.我很想看看是否有一个简单的pythonic方法可以通过单个查询来做到这一点.
query = "INSERT IGNORE ..."
cursor.execute(query)
# Last row was ignored
if cursor.lastrowid == 0:
这将执行INSERT IGNORE查询,如果忽略插入(重复),则lastrowid将为0.
This does an INSERT IGNORE query and if the insert is ignored (duplicate), the lastrowid will be 0.
这篇关于Python MySQLdb/MySQL INSERT IGNORE&检查是否被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!