Python MySQLdb / MySQL INSERT IGNORE & Checking if

2020-05-06 11:58发布

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

I could use a try/catch, but that's not very elegant. Was hoping that someone might have a cleaner and more elegant solution.

1条回答
相关推荐>>
2楼-- · 2020-05-06 12:37

Naturally, a final search after I post the question yields the result.

mysql - after insert ignore get primary key

However, this still requires a second trip to the database. I would love to see if there's a clean pythonic way to do this with a single query.

query = "INSERT IGNORE ..."
cursor.execute(query)

# Last row was ignored
if cursor.lastrowid == 0:

This does an INSERT IGNORE query and if the insert is ignored (duplicate), the lastrowid will be 0.

查看更多
登录 后发表回答