【问题标题】:List index out of range error during processing the long string SQL field处理长字符串 SQL 字段时出现 List index out of range 错误
【发布时间】: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 循环,因此文件中没有出现&lt;field&gt; 标记。

【问题讨论】:

    标签: python sql xml pyodbc


    【解决方案1】:

    查看您在 GitHub 中的代码,我认为问题可能在于您实际上没有正确填充 columns 数组,将其留空。这可以解释超出范围的错误。

    我将 AdventureWorks2012 数据库加载到我自己的 SQL Server 中,并从您的代码中运行原始的 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 文件,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2020-02-03
      相关资源
      最近更新 更多