我有一个连接到SQL数据库的工作脚本,然后将查询数据写入csv
文件。
它看起来像这样:
mydb = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=gamerTest;"
"Database=rpg_games;"
"uid=x;pwd=x")
cursor = mydb.cursor()
sql = """SELECT TOP (1000) *
FROM [rpg_games].[dbo].[myGames]"""
cursor.execute(sql)
row = cursor.fetchall()
with open('testing_games_list.csv', 'w', newline='') as f:
a = csv.writer(f, delimiter=',')
a.writerow(["My_Header_1", "My_Header_2"]) # how to automate?
a.writerows(row)
我希望脚本以编程方式打印使用a.writerow
的所有数据库表列名,但我不知道如何做到这一点,或者如果这是可能的。
有办法做到这一点吗?
谢谢!
这里的文档说,您应该查看cursor.description
。它包含列名和其他信息。