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

时间:2017-07-18 13:16:05

标签: 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()

我知道它只会是一行代码 - 我真的不知道该怎么做。

作为一个额外的复杂功能,遗憾的是我只能使用Python 2.7本机库,例如etree - 我无法在工作中下载第三方Python库。提前感谢您提供任何帮助或建议。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

您是否考虑过从数据库中返回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
相关问题