首页 > 解决方案 > 使用 Python 将 XML 文件存储到 MS SQL DB

问题描述

我的 MSSQL DB 表包含以下结构:

create table TEMP
(
  MyXMLFile XML

)

使用 Python,我尝试将本地存储的 .XML 文件加载到 MS SQL DB 中(不需要 XML 解析)

以下是 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')

# 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()

但是代码将 XML 路径存储在 MYXMLFile 列中,而不是 XML 文件中。我提到了lxml图书馆和其他教程。但是,我没有遇到直接存储文件的方法。

请任何人都可以帮助我。我刚刚开始研究 Python。

标签: pythonsql-serverxmllxml

解决方案


这是使用 Python 将 .XML 文件直接加载到 MS SQL SB 中的解决方案。

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()

推荐阅读