【问题标题】:Python - Convert XML field from SQL SERVER into XML FILE using pyodbcPython - 使用 pyodbc 将 SQL SERVER 中的 XML 字段转换为 XML 文件
【发布时间】:2016-03-04 14:32:04
【问题描述】:

我有下一个代码:

import pypyodbc as pyodbc

cnxn = pyodbc.connect(
    'Trusted_Connection=yes;DRIVER={SQL Server};SERVER=localhost;DATABASE=HOLA;UID=sa;PWD=HOLAMUNDO'
)

idPerson = 2

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM prueba WHERE id=?', (idPerson,))
for row in cursor.fetchall():
    print(row)

这很好用,并且选定的 XML 字段具有下一个格式:

<PERSON>
  <INFO>
    <NAME>Charlie</NAME>
    <LASTNAME>Brown</LASTNAME>
  </INFO>
</PERSON>

如何获取该字段并将其保存在目录中的新 XML 文件中...?

这是我的数据库的脚本:

USE [HOLA]
GO
/****** Object:  Table [dbo].[prueba]    Script Date: 04/03/2016 8:29:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[prueba](
    [id] [int] NOT NULL,
    [xml] [xml] NULL,
 CONSTRAINT [PK_prueba] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

【问题讨论】:

  • 只需将row 字符串保存到文件中。

标签: python sql-server xml pyodbc


【解决方案1】:

解决了,下个方法……

import pypyodbc as pyodbc
import urllib
from xml.dom.minidom import parse, parseString
xmlpath = "example.xml"

cnxn = pyodbc.connect(
    'Trusted_Connection=yes;DRIVER={SQL Server};SERVER=localhost;DATABASE=HOLA;UID=sa;PWD=HOLAMUNDO'
)

idPerson = 2

cursor = cnxn.cursor()
cursor.execute('SELECT id, xml FROM prueba WHERE id=?', (idPerson,))

for row in cursor.fetchall():
    print row[1]

xml = row[1]

#Generate the xml file from the string
dom = parseString(xml)

# Write the new xml file
xml_str = dom.toprettyxml(indent="  ")
with open("example.xml", "w") as f:
    f.write(xml_str)

【讨论】:

  • 要使其适用于 Python 3,请更改为 with open("example.xml", "wb") as f
  • 另外,如果有人遇到编码错误,我使用:f.write(xml_str.encode('utf8'))
猜你喜欢
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 2021-11-21
  • 2018-12-22
  • 2019-04-11
相关资源
最近更新 更多