2017-07-18 53 views
1

我試圖將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庫。在此先感謝您的任何幫助或建議。

+1

'write()'是'ElementTree'實例上的方法,但您可以在類上調用它。表示您的表格行的XML結構的根元素應該是一個參數。 'ET.ElementTree(root).write(file)'是否工作(假設'root'是那個根元素)? – mzjn

回答

1

[解決]供將來參考,有到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() 
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 
相關問題