Skip to content

Instantly share code, notes, and snippets.

@ryanbekabe
Forked from madan712/export_db_csv.py
Created March 9, 2023 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanbekabe/62f3668b013cf219ac6a2717584798c3 to your computer and use it in GitHub Desktop.
Save ryanbekabe/62f3668b013cf219ac6a2717584798c3 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')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment