Created
August 13, 2018 13:19
-
-
Save wesleyit/740c53c114105808bf20de804eab4df3 to your computer and use it in GitHub Desktop.
Get a CSV file from a SQL query
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
| import sys | |
| import pyodbc as odbc | |
| import datetime | |
| dsn = sys.argv[1] | |
| query_file = sys.argv[2] | |
| csv_file = sys.argv[3] | |
| print(f'Connecting to {dsn}') | |
| print(f'Executing {query_file}') | |
| print(f'Saving to {csv_file}\n') | |
| conn = odbc.connect(dsn) | |
| cursor = conn.cursor() | |
| cursor.execute(open(query_file).read()) | |
| print('Query executed. Fetching results...\n') | |
| counter = 0 | |
| with open(csv_file, 'w') as f: | |
| columns = list(zip(*cursor.description))[0] | |
| c_size = len(columns) | |
| data = {} | |
| for i, v in enumerate(columns): | |
| f.write(v) | |
| if i < c_size - 1: f.write(';') | |
| f.write('\n') | |
| while True: | |
| row = cursor.fetchone() | |
| counter += 1 | |
| if not row: | |
| break | |
| else: | |
| for i, v in enumerate(columns): | |
| reg = row[i] | |
| if type(reg) == datetime.datetime: reg = reg.isoformat() | |
| data[v] = reg | |
| f.write(str(reg)) | |
| if i < c_size - 1: f.write(';') | |
| f.write('\n') | |
| if counter % 1000 == 0: | |
| sys.stdout.write(f'\rProcessing line {counter} of {cursor.rowcount}.') | |
| print('\nDone!\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment