Skip to content

Instantly share code, notes, and snippets.

@madan712
Created June 27, 2019 20:12
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save madan712/f27ac3b703a541abbcd63871a4a56636 to your computer and use it in GitHub Desktop.
Save madan712/f27ac3b703a541abbcd63871a4a56636 to your computer and use it in GitHub Desktop.
Python - Export database table to csv file
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')
@CookieLau
Copy link

Really helps! :)

@ZWuMac
Copy link

ZWuMac commented Apr 8, 2024

Nice :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment