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 Python to query MySQL with multiple conditions?
- How can I use Python and MySQL to create a login system?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to authenticate MySQL on Windows?
- How can I connect Python to a MySQL database using an Xserver?
- How can I use the "order by" statement in Python to sort data in a MySQL database?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How do I connect to a MySQL database using Python and MySQL Workbench?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
See more codes...