Skip to content

Instantly share code, notes, and snippets.

@lmorillas
Last active October 8, 2015 10:16
Show Gist options
  • Save lmorillas/e1d236d32bcd0f9b831f to your computer and use it in GitHub Desktop.
Save lmorillas/e1d236d32bcd0f9b831f to your computer and use it in GitHub Desktop.
convert a mysql table to csv
'''
table_to_csv converts a table
db_to_csv converts all the tables
'''
import MySQLdb
import csv
# configure
DB_HOST = 'localhost'
DB_USER = 'xxxxxx'
DB_PASS = 'yyyyyy'
DB_NAME = 'zzzzzz'
# connection & cursor
connection_data = [DB_HOST, DB_USER, DB_PASS, DB_NAME]
conn = MySQLdb.connect(*connection_data)
cur = conn.cursor()
def table_to_csv(table):
cur.execute('select * from ' + table)
f = open(table+'.csv', 'w')
fw = csv.writer(f)
fw.writerow([r[0] for r in cur.description])
fw.writerows(cur.fetchall())
f.close()
def db_to_csv():
cur.execute('show tables')
tables = [t[0] for t in cur.fetchall() ]
for table in tables:
table_to_csv(table)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment