Skip to content

Instantly share code, notes, and snippets.

@nulconaux
Created June 16, 2022 17:13
Show Gist options
  • Select an option

  • Save nulconaux/8b22f03cb934efc571ec90746507510d to your computer and use it in GitHub Desktop.

Select an option

Save nulconaux/8b22f03cb934efc571ec90746507510d to your computer and use it in GitHub Desktop.
MySQL to CSV
import pymysql
def execute(c, command):
c.execute(command)
return c.fetchall()
db = pymysql.connect(host='', port=3306, user='root', passwd='', db='', use_unicode=True, 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