Skip to content

Instantly share code, notes, and snippets.

@shreyakupadhyay
Last active May 29, 2017 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shreyakupadhyay/d5f97e2bb65476109fe2c61c793da1e7 to your computer and use it in GitHub Desktop.
Save shreyakupadhyay/d5f97e2bb65476109fe2c61c793da1e7 to your computer and use it in GitHub Desktop.
Insert any dictionary data into mysql
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root", #give your mysql database username
passwd="db password", #give mysql database password
db="db name") #give mysql database name
x = conn.cursor()
'''
insert into mysql columns
'''
def storeData(dic):
for key in dic.keys():
# alter table in case the mysql column name is not found
try:
query = "show columns from table_name like " + "'" + key + "'" #give mysql table_name
val = x.execute(query)
if (val==0):
query_add = "ALTER TABLE table_name ADD %s VARCHAR(500)" % (key) #give mysql table_name
x.execute(query_add)
print "yes"
except:
conn.rollback()
# insert into mysql columns
for key in dic.keys():
dic[key] = "'"+dic[key]+"'"
column = ", ".join(dic.values())
column_values = ', '.join(dic.keys())
query_insert = "INSERT INTO product_details (%s) VALUES (%s) " % (column_values,column)
print query_insert
x.execute(query_insert)
conn.commit()
conn.close()
#give your dictionary in the below format
dic = {'Alpha':'1','Beta':'2'}
storeData(dic)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment