Last active
May 29, 2017 09:12
-
-
Save shreyakupadhyay/d5f97e2bb65476109fe2c61c793da1e7 to your computer and use it in GitHub Desktop.
Insert any dictionary data into mysql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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