-
-
Save ryanbekabe/62f3668b013cf219ac6a2717584798c3 to your computer and use it in GitHub Desktop.
Python - Export database table to csv file
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 mysql.connector | |
def fetch_table_data(table_name): | |
# The connect() constructor creates a connection to the MySQL server and returns a MySQLConnection object. | |
cnx = mysql.connector.connect( | |
host='localhost', | |
database='schema', | |
user='user', | |
password='password' | |
) | |
cursor = cnx.cursor() | |
cursor.execute('select * from ' + table_name) | |
header = [row[0] for row in cursor.description] | |
rows = cursor.fetchall() | |
# Closing connection | |
cnx.close() | |
return header, rows | |
def export(table_name): | |
header, rows = fetch_table_data(table_name) | |
# Create csv file | |
f = open(table_name + '.csv', 'w') | |
# Write header | |
f.write(','.join(header) + '\n') | |
for row in rows: | |
f.write(','.join(str(r) for r in row) + '\n') | |
f.close() | |
print(str(len(rows)) + ' rows written successfully to ' + f.name) | |
# Tables to be exported | |
export('TABLE_1') | |
export('TABLE_2') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment