Skip to content

Instantly share code, notes, and snippets.

@mindcruzer
Created September 1, 2015 05:37
Show Gist options
  • Save mindcruzer/f873a90bf4e37ac572bf to your computer and use it in GitHub Desktop.
Save mindcruzer/f873a90bf4e37ac572bf to your computer and use it in GitHub Desktop.
"""
Convert a CSV file to a series of SQL INSERT statements.
ex.
> python csv_to_sql.py data.csv dbo.SomeTable > data.sql
"""
import sys
if len(sys.argv) != 3:
print 'Provide the CSV file name and table name.'
print 'ex. python csv_to_sql.py data.csv dbo.SomeTable'
exit()
csv_file = sys.argv[1]
table_name = sys.argv[2]
with open(csv_file) as f:
columns = f.readline().rstrip()
print 'DELETE FROM %s;' % table_name
print 'SET IDENTITY_INSERT %s ON' % table_name
for line in f:
print 'INSERT INTO %s (%s) VALUES (%s);' % (table_name, columns, line.strip())
print 'SET IDENTITY_INSERT %s OFF' % table_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment