Last active
October 8, 2015 10:16
-
-
Save lmorillas/e1d236d32bcd0f9b831f to your computer and use it in GitHub Desktop.
convert a mysql table to csv
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
''' | |
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