Last active
October 12, 2022 11:00
-
-
Save ruanbekker/f4c5d917dd4d1b777b39c86240948dd2 to your computer and use it in GitHub Desktop.
Dump MySQL Data to CSV with Python
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
# 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) |
Thanks a lot. It works.
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
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?
Good job
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")
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'))
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
A couple of edits:
TypeError: a bytes-like object is required, not 'str'
, which I fixed by changingwb
to justw
in line 14