Глядя на ваш код в GitHub, я думаю, что проблема может заключаться в том, что вы на самом деле неправильно заполняете массив columns
, оставляя его пустым. Это объясняет ошибки, выходящие за пределы допустимого диапазона.
Я загрузил базу данных AdventureWorks2012 на свой собственный сервер SQL и запустил исходный файл columnsQuery
SQL из вашего кода:
select column_name
from information_schema.columns
where table_name = 'HumanResources.Department'
и это не дало результатов для имен столбцов:
![enter image description here](https://i.stack.imgur.com/B0ftL.png)
Однако изменение запроса дало правильные результаты имени столбца:
![enter image description here](https://i.stack.imgur.com/SQfpF.png)
Полный сценарий, который я использовал, был следующим (с некоторым кодом, скопированным из вашего):
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, подобный :
![enter image description here](https://i.stack.imgur.com/vzhrh.png)
Надеюсь, это даст вам возможность поработать.