Skip to content

Instantly share code, notes, and snippets.

@ruanbekker
Last active October 12, 2022 11:00
Show Gist options
  • Save ruanbekker/f4c5d917dd4d1b777b39c86240948dd2 to your computer and use it in GitHub Desktop.
Save ruanbekker/f4c5d917dd4d1b777b39c86240948dd2 to your computer and use it in GitHub Desktop.
Dump MySQL Data to CSV with Python
# requirement: python-mysqldb
import MySQLdb as dbapi
import sys
import csv
QUERY='SELECT * FROM mydb.people;'
db=dbapi.connect(host='localhost',user='root',passwd='password')
cur=db.cursor()
cur.execute(QUERY)
result=cur.fetchall()
c = csv.writer(open('dbdump01.csv', 'wb'))
for x in result:
c.writerow(x)
@topsbomalink
Copy link

You may also need to add string encoding to the open file writer:
encoding='utf-8'
c = csv.writer(open('user_dump01.csv', 'w',encoding='utf-8'))

@Anas-Dew
Copy link

result = DB.query('select * from fb')
c = csv.writer(open('dbdump01.csv', 'w'))
for x in result:
c.writerow(x)

This works cool

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