python-mysqlHow can I export data from a MySQL database to a CSV file using Python?
Using Python to export data from a MySQL database to a CSV file is a simple process. The following example code can be used to accomplish this task:
import csv
import MySQLdb
# Connect to the database
db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="database")
# Create a Cursor object to execute queries
cur = db.cursor()
# Select data from table using SQL query
cur.execute("SELECT * FROM table_name")
# Create a file and write the data to it
with open('filename.csv', 'w') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow([i[0] for i in cur.description]) # write headers
writer.writerows(cur)
# Close the connection
db.close()
This code will create a CSV file called filename.csv
and write the data from the table table_name
in the database database
to it.
The code consists of the following parts:
import csv
andimport MySQLdb
- imports the necessary modules for working with CSV files and MySQL databases.db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="database")
- establishes a connection to the MySQL database.cur = db.cursor()
- creates a cursor object to execute queries.cur.execute("SELECT * FROM table_name")
- selects data from the table using a SQL query.with open('filename.csv', 'w') as f:
- creates a file and opens it for writing.writer = csv.writer(f, delimiter=',')
- creates a CSV writer object.writer.writerow([i[0] for i in cur.description])
- writes the headers to the file.writer.writerows(cur)
- writes the data from the cursor object to the file.db.close()
- closes the connection to the database.
Helpful links
More of Python Mysql
- How do I use a SELECT statement in Python to query a MySQL database?
- How do I access MySQL using Python?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I fix a "MySQL server has gone away" error when using Python?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Python and MySQL to create a login system?
- How can I use the "order by" statement in Python to sort data in a MySQL database?
- How do I insert NULL values into a MySQL table using Python?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
See more codes...