If no rows are returned then it's probably because there is no data in the table with the requested firstname
. Try adding some debugging to your code and use a parameterised query rather than string concatenation:
cursor.execute("SELECT id FROM myguests WHERE firstname = %s", (title,))
row = cursor.fetchall()
print 'Got row: {!r}'.format(row) # some debugging
if row:
print "Record for {} already exists".format(title)
else:
print "List is empty, attempting to insert"
cursor.execute(title_query, (title,))
But there is a potential race condition with this approach; what if some other process adds the value to the database between the initial check and the subsequent insert? Depending on your application this may or may not be a problem.
Regarding "insert if not exists", one way is to set a UNIQUE INDEX on the firstname
column. and then simply attempt to insert a new row without checking first. If a row exists with the same value for firstname
the insert will fail. If no such row exists, the insert will be attempted (it might still fail, but for other reasons). Your code needs to handle insertion failure due to duplicate key.
Or you could investigate use of INSERT IGNORE into myguests ...
, or some of the other options discussed here: How to 'insert if not exists' in MySQL?.
But are you really sure that firstname
should be unique? It seems to me likely that many guests could have the same first name.