使用Python将Oracle数据库表导出为XML文件?
问题描述:
我试图将Oracle 12c数据库中保存的表导出为组成XML文件,以便Oracle表中的每一行生成1个XML文件。为此,我正在使用Python 2.7库xml.etree.ElementTree
,但我在documentation中看不到任何可以让我这样做的任何内容。基本上我需要在这一点上是:使用Python将Oracle数据库表导出为XML文件?
import cx_Oracle
from xml.etree import ElementTree as ET
SQL = ''.join([ 'SELECT * FROM ', table_name ])
connection = cx_Oracle.connect('username/[email protected]')
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 - 我无法在工作中下载第三方Python库。在此先感谢您的任何帮助或建议。
答
[解决]供将来参考,有到Oracle数据导出到使用Python和cx_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/[email protected]')
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()
答
您是否考虑过从数据库中返回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
'write()'是'ElementTree'实例上的方法,但您可以在类上调用它。表示您的表格行的XML结构的根元素应该是一个参数。 'ET.ElementTree(root).write(file)'是否工作(假设'root'是那个根元素)? – mzjn