Adding new entries to database – Python & MySQL

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='',

# 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

# close connection

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s