处理长字符串 SQL 字段时出现列表索引超出范围错误

List index out of range error during processing the long string SQL field

长话短说 - 我在 Python 中创建了一个终端仿真器,旨在与 MS SQL 数据库进行交互。我刚刚实现了一个 SQL-XML 转换机制,允许用户将选择的 table 导出到预先格式化的 XML 文件中,但是当我尝试处理来自AdventureWorks2012->HumanResources.Department table,包含很长的字符串,我收到 List index out of range 错误 - 这不适用于更小、更-自定义数据库中的人道字段。

Link 回购:https://github.com/jsarnowski96/pysql-console

如何使用小型自定义 tables:

如何使用 AdventureWorks2012 数据库:

HumanResources.Departmenttable的内容:

疑似代码段:

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> 标记。

查看您在 GitHub 中的代码,我认为问题可能在于您实际上没有正确填充 columns 数组,而是将其留空。这将解释 out-of-运行ge 错误。

我将 AdventureWorks2012 数据库加载到我自己的 SQL 服务器和 运行 来自您的代码的原始 columnsQuery SQL:

select column_name
from information_schema.columns
where table_name = 'HumanResources.Department'

这没有给出列名的结果:

但是,更改查询给出了正确的列名结果:

我使用的完整脚本如下(部分代码是从你那里复制的):

import pyodbc

dbConnection  = pyodbc.connect('Driver={SQL Server};'
                      'Server=CPMLT5YHJMQ2;'
                      'Database=AdventureWorks2012;'
                      'Trusted_Connection=yes;')

table = 'HumanResources.Department';

columnsQuery = list("SELECT name FROM sys.columns WHERE OBJECT_ID = OBJECT_ID('" + table + "')")
columnsQuery = ''.join(columnsQuery)

cursor = dbConnection .cursor()
cols = cursor.execute(columnsQuery).fetchall()
columns = list(str(c) for c in cols)
columns = list([c.replace('(','').replace(')','').replace(' ','').replace("'",'').replace(',','').strip() for c in columns])

selectQuery = list("select * from " + table)
selectQuery = ''.join(selectQuery)
rows = cursor.execute(selectQuery).fetchall()

with open("test.xml", "w+", newline='') as xmlFile:
    xmlFile.write("<?xml version='1.0' ?>\n")
    xmlFile.write("<%s>\n" % table)
    indent_count = 1
    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]))
        xmlFile.write("\t</field>\n")
        indent_count = 1
    xmlFile.write("</%s>\n" % table)
    xmlFile.close()

这会生成一个 xml 文件,例如:

我希望这能给你一些工作的机会。