So I'm doing a lot of inserts which only I want to insert into a certain table when the name doesn't "exist" in the table yet, i.e. I don't want to have any duplicates. I'm approaching it this way now:
def create_artist(artist_name):
artistid = has_artist(artist_name)
if not artistid:
sql['cursor'].execute("INSERT INTO artists VALUES (NULL, ?)", (artist_name,))
artistid = has_artist(artist_name)
return artistid[0]
def has_artist(artist_name):
sql['cursor'].execute("SELECT id FROM artists WHERE artist_name = ?", (artist_name,))
return (sql['cursor'].fetchone())
It basically looks up if there is an artist with the same name in the table, if not, it inserts one and else it just returns the lookup. There has to be a better way of doing this, is it possible to move this whole process into a query so I will be able to move this all to SQL?
Look into INSERT IGNORE. This will require you to have a UNIQUE index on your table that will cause the IGNORE to trigger.
INSERT IGNORE INTO artists VALUES (NULL, ?)