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)
@StoppingBuck
Copy link

A couple of edits:

  • I got an error 'No database selected', so I had to add db='dbname' to the dbapi.connect()
  • Then I got an error TypeError: a bytes-like object is required, not 'str', which I fixed by changing wb to just w in line 14

@litanur
Copy link

litanur commented Sep 19, 2018

Thanks a lot. It works.

@tal88
Copy link

tal88 commented Sep 18, 2019

I'm getting a "No Module named MySql DB" error when running this in Anaconda with Python 3.7.

Is this because Python 3.X does not support MySQLDB and I need to downgrade to 2.7?

Thanks

@lidemarm
Copy link

Thank you so much! this worked perfectly for me.

I just have a question... What can I do to also include the column names in the CSV file?

@balasmeh
Copy link

balasmeh commented Dec 2, 2019

Good job

@singhashupratap
Copy link

Also, you can do through pandas

import pandas as pd
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()

result.to_csv("./Desktop/testdump.csv")

@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