Created
February 28, 2017 20:50
-
-
Save jcook793/2a08a146a7f561f2783aade92a5ba326 to your computer and use it in GitHub Desktop.
Takes a SQL file, executes it and generates a CSV file with column names for the output
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 getpass | |
import pymysql | |
import csv | |
def main(): | |
host = raw_input("DB hostname: ") | |
db = raw_input("Schema name: ") | |
user = raw_input("Username: ") | |
password = getpass.getpass("Password: ") | |
query_file = raw_input("Input SQL filename: ") | |
csv_file = raw_input("Output CSV filename: ") | |
print "Connecting to %s..." % host | |
connection = pymysql.connect(host=host, user=user, password=password, db=db) | |
cursor = connection.cursor() | |
print "Reading query file %s..." % query_file | |
with open(query_file, 'r') as fp: | |
print("Executing query...") | |
cursor.execute(fp.read()) | |
print "Fetching results..." | |
columns = [i[0] for i in cursor.description] | |
results = cursor.fetchall() | |
with open(csv_file, 'w') as fp: | |
print "Writing %s..." % csv_file | |
csv_writer = csv.writer(fp) | |
csv_writer.writerow(columns) | |
csv_writer.writerows(results) | |
print "Cleaning up..." | |
cursor.close() | |
connection.close() | |
print "Done!" | |
if __name__ == '__main__': main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment