Insert into table if item doesn't exist already

Soldato
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
I'm wanting to insert an item into a table so long as it doesn't already exist in a table. For this I have this code inside a for loop (the for loop just loops through a list of dictionaries, every new dictionary is assigned to the tempDict variable)

PHP:
self._dbase.query("SELECT PROGTITLE, SUBTITLE FROM PROGRAMME WHERE PROGTITLE=\""+tempDict["PROGTITLE"]
                   +" and SUBTITLE="+tempDict["SUBTITLE"]+"\"")
progResult = self._dbase.store_result()
if progResult.num_rows() == 0:
   self._cursor.execute("""INSERT INTO PROGRAMME(GENREID,PROGTITLE,SUBTITLE,EPISODE,YEAR,DIRECTOR,PERFORMERS,FILM,WIDESCREEN,
                           BNW,STARRATING,CERTIFICATE,DESCRIPTION) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                           (genreId,tempDict["PROGTITLE"],tempDict["SUBTITLE"],tempDict["EPISODE"],tempDict["YEAR"],
                           tempDict["DIRECTOR"],tempDict["PERFORMERS"],tempDict["FILM"],tempDict["WIDESCREEN"],tempDict["BNW"],
                           tempDict["STARRATING"],tempDict["CERTIFICATE"],tempDict["DESCRIPTION"]))

Problem is it is still inserting duplicates, and I'm not sure why? progResult.fetch_row() never returns anything (i.e. a duplicate), even though it should
 
Last edited:
Sorted it, I'm not sure why but changing the code like so worked!

PHP:
self._cursor.execute("""SELECT PROGTITLE, SUBTITLE FROM PROGRAMME WHERE PROGTITLE=%s and SUBTITLE=%s"""
                        ,(tempDict["PROGTITLE"],tempDict["SUBTITLE"]))
progResult = self._cursor.fetchone()
if progResult == None:
   self._cursor.execute("""INSERT INTO PROGRAMME(GENREID,PROGTITLE,SUBTITLE,EPISODE,YEAR,DIRECTOR,PERFORMERS,FILM,WIDESCREEN,
                        BNW,STARRATING,CERTIFICATE,DESCRIPTION) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                        (genreId,tempDict["PROGTITLE"],tempDict["SUBTITLE"],tempDict["EPISODE"],tempDict["YEAR"],
                        tempDict["DIRECTOR"],tempDict["PERFORMERS"],tempDict["FILM"],tempDict["WIDESCREEN"],tempDict["BNW"],
                        tempDict["STARRATING"],tempDict["CERTIFICATE"],tempDict["DESCRIPTION"]))
 
Back
Top Bottom