Last active
June 14, 2022 10:38
-
-
Save macleginn/44c117c4cc1f4d9b2abc63a8d2bd2e91 to your computer and use it in GitHub Desktop.
Export all tables from a MySQL database as .csv files using Python 3
This file contains hidden or 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 pymysql | |
def execute(c, command): | |
c.execute(command) | |
return c.fetchall() | |
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='mysql') #, charset='utf8') | |
c = db.cursor() | |
for table in execute(c, "show tables;"): | |
table = table[0] | |
cols = [] | |
for item in execute(c, "show columns from " + table + ";"): | |
cols.append(item[0]) | |
data = execute(c, "select * from " + table + ";") | |
with open(table + ".csv", "w", encoding="utf-8") as out: | |
out.write("\t".join(cols) + "\n") | |
for row in data: | |
out.write("\t".join(str(el) for el in row) + "\n") | |
print(table + ".csv written") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment