【问题标题】:Export Oracle database table as XML file using Python?使用 Python 将 Oracle 数据库表导出为 XML 文件?
【发布时间】:2017-12-23 09:20:36
【问题描述】:

我正在尝试将 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 库。提前感谢您的任何帮助或建议。

【问题讨论】:

  • write()ElementTree 实例上的方法,但您在类上调用它。代表表格行的 XML 结构的根元素应该是一个参数。 ET.ElementTree(root).write(file) 是否有效(假设 root 是那个根元素)?

标签: python xml oracle python-2.7 elementtree


【解决方案1】:

[已解决] 为了将来参考,使用 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()

【讨论】:

    【解决方案2】:

    您是否考虑过从数据库中返回 XML? Oracle DB 有大量的 XML 支持。

    这两个查询显示不同的功能;为其他人检查Oracle Manuals

    select xmlelement("Employees",
     xmlelement("Name", employees.last_name),
     xmlelement("Id", employees.employee_id)) as result
     from employees
     where employee_id > 200
    

     select dbms_xmlgen.getxml('
     select first_name
     from employees
     where department_id = 30') xml
     from dual
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多