python-mysqlHow can I convert data from a MySQL database to XML using Python?
Converting data from a MySQL database to XML using Python is a relatively straightforward process.
The following example code will first connect to a MySQL database, query the database for all data in a specified table, and then write the data to an XML file.
import mysql.connector
import xml.etree.ElementTree as ET
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="database"
)
# Create a cursor object
mycursor = mydb.cursor()
# Execute the query
mycursor.execute("SELECT * FROM table")
# Fetch all the rows
rows = mycursor.fetchall()
# Create the root element
root = ET.Element("root")
# Iterate over the rows
for row in rows:
# Create the child element
child = ET.SubElement(root, "child")
# Iterate over the columns
for col in row:
# Create the grandchild element
grandchild = ET.SubElement(child, "grandchild")
# Set the text of the grandchild element
grandchild.text = str(col)
# Create an XML file
xml_file = open("output.xml", "w")
# Write the XML tree to the file
xml_file.write(ET.tostring(root).decode())
# Close the XML file
xml_file.close()
The code above will generate an XML file named output.xml
with the following content:
<root>
<child>
<grandchild>1</grandchild>
<grandchild>John</grandchild>
<grandchild>Doe</grandchild>
</child>
<child>
<grandchild>2</grandchild>
<grandchild>Jane</grandchild>
<grandchild>Doe</grandchild>
</child>
</root>
The code consists of the following parts:
- Importing the necessary modules:
mysql.connector
to connect to the MySQL databasexml.etree.ElementTree
to create the XML tree
- Connecting to the database
- Creating a cursor object
- Executing the query
- Fetching all the rows
- Creating the root element
- Iterating over the rows
- Creating the child element
- Iterating over the columns
- Creating the grandchild element
- Setting the text of the grandchild element
- Creating an XML file
- Writing the XML tree to the file
- Closing the XML file
For more information, see the following links:
More of Python Mysql
- How can I use Python to interact with a MySQL database using YAML?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
- How do I show databases in MySQL using Python?
- How do I insert JSON data into a MySQL database using Python?
- How do Python and MySQL compare to MariaDB?
- How can I use Python to retrieve data from MySQL?
- How can I use Yum to install the MySQLdb Python module?
See more codes...