SkyeBoniwell
SkyeBoniwell

Reputation: 7092

How can I use Python and pyodbc to print out table column names?

I have a working script that connects to a SQL Database and then writes the query data to a csv file.

It looks like this:

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)

I want the script to programatically print all the database table column names using a.writerow but I can't figure out how to do that or if that's even possible.

Is there a way to do this?

Thanks!

Upvotes: 0

Views: 1139

Answers (1)

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

The documentation here says, you should look into cursor.description. It contains the column names, and other information.

Upvotes: 1

Related Questions