我正在尝试将 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/