Last active
November 20, 2021 00:55
-
-
Save Lbatson/8177359 to your computer and use it in GitHub Desktop.
Converts csv data to mysql insert statements
This file contains hidden or 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
#converts csv data to mysql insert statements | |
import csv | |
#prompt user for file name | |
filename = raw_input("Enter the csv file name: ") | |
tablename = raw_input("Enter db table name for insert statements: ") | |
# open csv file | |
with open(filename + '.csv', 'rb') as csvfile: | |
# store in dict | |
filereader = csv.DictReader(csvfile, delimiter=',', quotechar='"') | |
# convert list to column or values string | |
def sqlstring(slist, quotes): | |
s = '(' | |
for value in slist: | |
if quotes: | |
if value.find("'") != -1: | |
value = value.replace("'", "") | |
s += '\'' + value + '\'' + ',' | |
else: | |
s += value + ',' | |
s = s[:-1] | |
s += ')' | |
return s | |
try: | |
outfile = open(tablename + '_import.sql', 'w') | |
for row in filereader: | |
# create dict from row without blank values | |
newrow = {} | |
for key, value in row.iteritems(): | |
if value != '': | |
newrow[key] = value | |
# build column and value strings | |
cols = sqlstring(newrow.keys(), False) | |
vals = sqlstring(newrow.values(), True) | |
# create sql insert statement for row and execute | |
sql = 'INSERT INTO ' + tablename + ' ' + cols + ' VALUES ' + vals + ';\n' | |
outfile.write(sql) | |
except Exception, e: | |
print "Error: " + e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment