Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import copy
- import json
- import argparse
- import mysql.connector
- parser = argparse.ArgumentParser(description='Export an SQL database to either CSV or JSON')
- parser.add_argument('username', help='username for the database')
- parser.add_argument('database', help='name of database to export')
- parser.add_argument('--password', help='password for the user')
- args = parser.parse_args()
- cnx = mysql.connector.connect(user=args.username, database=args.database, password=args.password)
- cursor = cnx.cursor()
- cursor.execute("SHOW TABLES")
- tables = cursor.fetchall()
- data = {}
- for (table,) in tables:
- row_keys = []
- if table not in data:
- data[table] = []
- cursor.execute("DESCRIBE " + table)
- for i in cursor.fetchall():
- row_keys.append(i[0])
- cursor.execute("SELECT * FROM " + table)
- row = cursor.fetchall()
- temp = {}
- for i in row:
- # print(i)
- for j in range(len(row_keys)):
- temp[row_keys[j]] = i[j]
- # print(temp)
- data[table] += temp.copy()
- cursor.close()
- cnx.close()
- # print(json.dumps(data, indent=4, default=lambda x:str(x)))
- # print(data)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement