python - 使用 Python 将 Oracle 数据库表导出为 XML 文件?

标签 python xml oracle python-2.7 elementtree

我正在尝试将 Oracle 12c 数据库中保存的表导出到组成的 XML 文件中,以便 Oracle 表中的每一行都会生成 1 个 XML 文件。为此,我使用 Python 2.7 库 xml.etree.ElementTree,但我在 documentation 中看不到任何内容。这将使我能够做到这一点。基本上我现在需要的是:

import cx_Oracle
from xml.etree import ElementTree as ET

SQL = ''.join([ 'SELECT * FROM ', table_name ])
connection = cx_Oracle.connect('username/password@database')
cursor = connection.cursor()

for i in range(num_rows):

    ... #code works fine up to here

    file_name = i
    file_path = ''.join([ 'C:\..., file_name, '.xml ])
    file = open(file_path, 'w')
    cursor.execute(SQL)
    ET.ElementTree.write(file) #This line won't work
    cursor.close()
    file.close()

connection.close()

我知道这只是 1 行代码 - 我只是真的不知道该怎么做。

不幸的是,更复杂的是,我只能使用 Python 2.7 原生的库,例如 etree - 我无法在工作中下载第 3 方 Python 库。提前感谢您的任何帮助或建议。

最佳答案

[已解决]为了将来引用,使用 Python 和 cx_Oracle 将 Oracle 数据导出为 xml 格式需要两个单独的步骤。

1) 首先,由于某种原因,在 Python 中的初始 SQL 语句中,我们必须对我们尝试操作的 XMLtype 表使用别名,并将 .getClobVal() 添加到SQL 语句(第 3 行),如 here in Kishor Pawar's answer. 所述因此上面的代码就变成了:

1  import cx_Oracle
2 
3  SQL = ''.join([ 'SELECT alias.COLUMN_NAME.getClobVal() FROM XML_TABLE ])
4  connection = cx_Oracle.connect('username/password@database')
5  cursor = connection.cursor()

2) 在我的问题中,我错误地使用了游标 - 因此需要第 12 行的附加代码:cx_Oracle.Cursor.fetchone()。这实际上返回一个元组,因此我们需要最后的 [0] 来切出元组中包含的单个信息。

此外,需要使用 str() 将其转换为字符串(第 13 行)。

完成此操作后,不需要其他导入(例如 ElementTree)来生成 xml 文件;这是在第 15-16 行完成的。

6  for i in range(num_rows):
7 
8      file_name = i
9      file_path = ''.join([ 'C:\..., file_name, '.xml ])
10     file = open(file_path, 'w')
11     cursor.execute(SQL)
12     oracle_data = cx_Oracle.Cursor.fetchone(cursor_oracle_data)[0]
13     xml_data = str(oracle_data)
14
15     with open(file_path, 'w') as file:
16         file.write(xml_data)
17
18     file.close()
19
20 cursor.close()
21 connection.close()

关于python - 使用 Python 将 Oracle 数据库表导出为 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45167927/

相关文章:

python - Pandas 日期时间列的矢量化操作

python - Soundcloud API 在某些轨道上返回 403

xml - 在 Perl 中将类似 XML 的格式转换为 CSV

c# - 用c#检查一个表是否存在于oracle sql数据库中

sql - 在 Oracle SQL 中创建并填充 Varray

sql - Oracle 分析函数可折叠记录

python - 为什么默认值没有出现在我的 docopt 命令行参数字典中?

python - 按标签顺序对 html 内容进行分组

java - 如何为 Web 应用程序配置 log4j.xml?

c# - 将编码为 UTF-8 的 xml 文件转换为 ANSI