1

So i want to store my XML data to database using python connector to mysql.

import mysql.connector
from getpass import getpass
from mysql.connector import connect, Error
import xml.etree.ElementTree as ET

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="results"
)

if mydb:
    print ("Connected Successfully")
else:
    print ("Connection Not Established")

tree = ET.parse('report.xml')
res = tree.findall('entry')

for test in res:
    
    name = test.find('name').text
    verdict = test.find.int('verdict').text
    description = test.find('description').text
        
    report = """INSERT INTO test_executions (name,verdict,description)
                        VALUES(%s,%s,%s)"""

    cursor = mydb.cursor()
    cursor.execute(report,(name,verdict,description))
    mydb.commit()
    print("Data inserted successfully.")
    print(mycursor.rowcount, "record inserted.")

I already have this code but everytime i run it, it never go through the for loop and commit the insertion to my DB. Is there something wrong with the code?

  • See [this](https://stackoverflow.com/questions/1912434/how-to-parse-xml-and-count-instances-of-a-particular-node-attribute?rq=1). I think you need to call "findall" method on the root element and not the document. thus "tree.findall" should be "tree.getroot().findall('entry') – Meher Khiari Apr 30 '21 at 09:21

0 Answers0