Created
September 1, 2015 05:37
-
-
Save mindcruzer/f873a90bf4e37ac572bf to your computer and use it in GitHub Desktop.
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
""" | |
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