Store XML File into MS SQL DB using Python

Question:

My MSSQL DB table contains following structure:

create table TEMP
(
  MyXMLFile XML

)

Using Python, I a trying to load locally stored .XML file into MS SQL DB (No XML Parsing Required)

Following is Python code:

import pyodbc
import xlrd
import xml.etree.ElementTree as ET

print("Connecting..")
# Establish a connection between Python and SQL Server
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=TEST;'
                      'Database=test;'
                      'Trusted_Connection=yes;')
print("DB Connected..")

# Get XMLFile
XMLFilePath = open('C:HelloWorld.xml')

# Create Table in DB
CreateTable = """
create table test.dbo.TEMP
(

 XBRLFile XML

)
"""

# execute create table
cursor = conn.cursor()
try:
    cursor.execute(CreateTable)
    conn.commit()
except pyodbc.ProgrammingError:
    pass
print("Table Created..")

InsertQuery = """
INSERT INTO test.dbo.TEMP (
    XBRLFile
) VALUES (?)"""

# Assign values from each row
values = (XMLFilePath)

# Execute SQL Insert Query
cursor.execute(InsertQuery, values)

# Commit the transaction
conn.commit()

# Close the database connection
conn.close()

But the code is storing the XML path in MYXMLFile column and not the XML file. I referred lxml library and other tutorials. But, I did not encountered straight forward approach to store file.

Please can anyone help me with it. I have just started working on Python.

Asked By: user2961127

||

Answers:

Here, is solution to load .XML file directly into MS SQL SB using Python.

import pyodbc
import xlrd
import xml.etree.ElementTree as ET

print("Connecting..")
# Establish a connection between Python and SQL Server
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=TEST;'
                      'Database=test;'
                      'Trusted_Connection=yes;')
print("DB Connected..")

# Get XMLFile
XMLFilePath = open('C:HelloWorld.xml')
x = etree.parse(XBRLFilePath)          # Updated Code line
with open("FileName", "wb") as f:      # Updated Code line
    f.write(etree.tostring(x))         # Updated Code line

# Create Table in DB
CreateTable = """
create table test.dbo.TEMP
(

 XBRLFile XML

)
"""

# execute create table
cursor = conn.cursor()
try:
    cursor.execute(CreateTable)
    conn.commit()
except pyodbc.ProgrammingError:
    pass
print("Table Created..")

InsertQuery = """
INSERT INTO test.dbo.TEMP (
    XBRLFile
) VALUES (?)"""

# Assign values from each row
values = etree.tostring(x) # Updated Code line

# Execute SQL Insert Query
cursor.execute(InsertQuery, values)

# Commit the transaction
conn.commit()

# Close the database connection
conn.close()
Answered By: user2961127
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.