python - 使用 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。
解决方案
这是使用 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()
推荐阅读
- multithreading - 工作线程,具有特定“颜色”的作业,每种颜色只能运行一个作业,我需要什么同步原语?
- c# - 在 C# 中扩展第三方 dll
- python - 熊猫 - 从日期中提取的错误周
- google-drive-api - 如何开发自己的云存储,并可以访问其他用户,例如 Google Drive,但要简单得多?
- sql - 考虑两个表的 SQL 查询
- java - Spring Boot + Spring Security 的自定义登录页面
- c++ - 分配向量的前缀和并将结果存储在静态向量中
- scala - 火花动态分组多列
- sharepoint - 使用 REST API 将帖子回复到讨论板
- ios - 任何检测“UnsafeMutablePointer”的方法已被释放?