Last active
April 25, 2023 09:59
-
-
Save aimerneige/245582d209b8fb5df86570a9787c3eca to your computer and use it in GitHub Desktop.
read database and query all data into json
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 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") |
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
pip install mysql-connector-python