【发布时间】:2020-01-06 21:36:07
【问题描述】:
长话短说 - 我用 Python 创建了一个终端模拟器,用于与 MS SQL 数据库交互。我刚刚实现了一个 SQL-XML 转换机制,它允许用户将选定的表导出到预先格式化的 XML 文件中,但是当我尝试处理 AdventureWorks2012->HumanResources.Department 表中的数据时,包含很长的字符串,我收到 List index out of range 错误 - 这不适用于自定义数据库中更小、更人性化的字段。
回购链接:https://github.com/jsarnowski96/pysql-console
如何处理小型自定义表格:
它如何与 AdventureWorks2012 数据库一起使用:
HumanResources.Department 表的内容:
疑似代码:
with open(finalPath, "w+", newline='') as xmlFile:
xmlFile.write("<?xml version='1.0' ?>\n")
xmlFile.write("<%s>\n" % table)
for row in rows:
xmlFile.write("\t<field>\n")
indent_count += 1
for j in range(len(row)):
xmlFile.write("\t" * indent_count + "<%s>\n" % str(columns[j]))
xmlFile.write("\t" * (indent_count + 1) + "%s\n" % str(row[j]))
xmlFile.write("\t" * indent_count)
xmlFile.write("</%s>\n" % str(columns[j]))
indent_count = 1
xmlFile.write("\t</field>\n")
xmlFile.write("</%s>\n" % table)
print("SQL-XML conversion task finished successfully. File",fileName,"has been created.\n")
编辑:在使用 columns 迭代器将所有内容包装在顶层 for 循环中后,错误消失了,但它不会将任何行保存到目标文件中:
修改部分:
for i in range(len(columns)):
for row in rows:
xmlFile.write("\t<field>\n")
indent_count += 1
iterator = i
for j in range(len(row)):
xmlFile.write("\t" * indent_count + "<%s>\n" % str(columns[iterator]))
xmlFile.write("\t" * (indent_count + 1) + "%s\n" % str(row[j]))
xmlFile.write("\t" * indent_count)
xmlFile.write("</%s>\n" % str(columns[iterator]))
iterator += 1
indent_count = 1
xmlFile.write("\t</field>\n")
在我看来,在上述情况下,程序甚至没有执行第二个for 循环,因此文件中没有出现<field> 标记。
【问题讨论】: