Checking to see if an entry exists in the database, if not, then add it
Currently, in the database we only have two names, ‘Shaniqua’ and ‘Jose’
But the new list of names contains a new person ‘Latifah’.
Here is how the db can be updated
from MySQLdb import connect # this is the list of new names list_new_names = ['Shaniqua','Jose','Latifah'] # conenct to database db_connect = connect(host='127.0.0.1', user='usrName', passwd='password123', db='db_samp') # get cursor db_cursor = db_connect.cursor() # make query and get data db_cursor.execute('SELECT `name` FROM `t_main`') tup_names = db_cursor.fetchall() # remove tupples and make list list_names = [i for j in tup_names for i in j] # now make sets set_old_names = set(list_names) set_new_names = set(list_new_names) # find difference in sets and make list list_add_names = list(set_new_names.difference(set_old_names)) # now add items on the list to the db table for str_each_name in list_add_names: db_cursor.execute('INSERT INTO `t_main` (name) VALUES("%s")'% str_each_name) # commit all changes db_connect.commit() # close connection db_connect.close()