Skip to content

Instantly share code, notes, and snippets.

@macleginn
Last active June 14, 2022 10:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save macleginn/44c117c4cc1f4d9b2abc63a8d2bd2e91 to your computer and use it in GitHub Desktop.
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
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