Skip to content

Instantly share code, notes, and snippets.

@aimerneige
Last active April 25, 2023 09:59
Show Gist options
  • Save aimerneige/245582d209b8fb5df86570a9787c3eca to your computer and use it in GitHub Desktop.
Save aimerneige/245582d209b8fb5df86570a9787c3eca to your computer and use it in GitHub Desktop.
read database and query all data into json
import os
import mysql.connector
# edit this to your database
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="example",
database="example",
)
mycursor = mydb.cursor()
mycursor.execute("show tables")
# query all tables
tables = []
for x in mycursor:
tables.append(x[0])
for table in tables:
json_path = os.path.join(os.getcwd(), "result", table + '.json')
if os.path.exists(json_path):
os.remove(json_path)
# read all table data and write it into json file
sql_command = f"select * from `{table}`"
mycursor.execute(sql_command)
myresult = mycursor.fetchall()
with open(json_path, 'a') as f:
f.write("[\n")
for i in range(len(myresult)):
f.write(" {\n")
for j in range(len(myresult[i])):
f.write(f' "{mycursor.column_names[j]}": "{myresult[i][j]}",\n')
f.write(" },\n")
f.write("]\n")
@aimerneige
Copy link
Author

aimerneige commented Apr 25, 2023

All files will be written into ./result, create a clean directory before you run this script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment