I am looking for a simple way to query an update or insert based on if the row exists in the first place. I am trying to use Python s MySQLdb right now. This is how I execute my query:
self.cursor.execute("""UPDATE `inventory`
SET `quantity` = `quantity`+{1}
WHERE `item_number` = {0}
""".format(item_number,quantity));
I have seen four ways to accomplish this:
DUPLICATE KEY. Unfortunately the primary key is already taken up as a unique ID so I can t use this.
REPLACE. Same as above, I believe it relies on a primary key to work properly.
mysql_affected_rows()
. Usually you can use this after updating the row to see if anything was affected. I don t believe MySQLdb in Python supports this feature.Of course the last ditch effort: Make a SELECT query, fetchall, then update or insert based on the result. Basically I am just trying to keep the queries to a minimum, so 2 queries instead of 1 is less than ideal right now.
Basically I am wondering if I missed any other way to accomplish this before going with option 4. Thanks for your time.