Advertisement
Guest User

Untitled

a guest
Feb 28th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. import getpass
  2. import pymysql
  3. import csv
  4.  
  5. def main():
  6. host = raw_input("DB hostname: ")
  7. db = raw_input("Schema name: ")
  8. user = raw_input("Username: ")
  9. password = getpass.getpass("Password: ")
  10. query_file = raw_input("Input SQL filename: ")
  11. csv_file = raw_input("Output CSV filename: ")
  12.  
  13. print "Connecting to %s..." % host
  14. connection = pymysql.connect(host=host, user=user, password=password, db=db)
  15. cursor = connection.cursor()
  16.  
  17. print "Reading query file %s..." % query_file
  18. with open(query_file, 'r') as fp:
  19. print("Executing query...")
  20. cursor.execute(fp.read())
  21.  
  22. print "Fetching results..."
  23. columns = [i[0] for i in cursor.description]
  24. results = cursor.fetchall()
  25.  
  26. with open(csv_file, 'w') as fp:
  27. print "Writing %s..." % csv_file
  28. csv_writer = csv.writer(fp)
  29. csv_writer.writerow(columns)
  30. csv_writer.writerows(results)
  31.  
  32. print "Cleaning up..."
  33. cursor.close()
  34. connection.close()
  35.  
  36. print "Done!"
  37.  
  38. if __name__ == '__main__': main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement