Advertisement
Guest User

Untitled

a guest
Sep 18th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. import copy
  2. import json
  3. import argparse
  4. import mysql.connector
  5.  
  6. parser = argparse.ArgumentParser(description='Export an SQL database to either CSV or JSON')
  7. parser.add_argument('username', help='username for the database')
  8. parser.add_argument('database', help='name of database to export')
  9. parser.add_argument('--password', help='password for the user')
  10.  
  11. args = parser.parse_args()
  12.  
  13. cnx = mysql.connector.connect(user=args.username, database=args.database, password=args.password)
  14. cursor = cnx.cursor()
  15.  
  16. cursor.execute("SHOW TABLES")
  17. tables = cursor.fetchall()
  18.  
  19. data = {}
  20.  
  21. for (table,) in tables:
  22. row_keys = []
  23. if table not in data:
  24. data[table] = []
  25. cursor.execute("DESCRIBE " + table)
  26. for i in cursor.fetchall():
  27. row_keys.append(i[0])
  28.  
  29. cursor.execute("SELECT * FROM " + table)
  30. row = cursor.fetchall()
  31.  
  32. temp = {}
  33. for i in row:
  34. # print(i)
  35. for j in range(len(row_keys)):
  36. temp[row_keys[j]] = i[j]
  37.  
  38. # print(temp)
  39.  
  40. data[table] += temp.copy()
  41.  
  42. cursor.close()
  43. cnx.close()
  44.  
  45. # print(json.dumps(data, indent=4, default=lambda x:str(x)))
  46. # print(data)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement