Python Forum

Full Version: EXPORT FROM SQL SERVER TO CSV
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The below code works however, whenever it gets exported, the headers for each column is missing. I need it to include all headers please advise

import pyodbc
import csv

conn =("Driver={SQLSERVER Native Client 11.0};"
"Server = blah"
"database = mydb;"

cursor = coon.cursor()
sql = """Select top 5 * from mytable"""
cursor.execute(sql)

row = cursor.fetchall()
with open('test.csv', 'w', newline= '') as f:
a = csv.writer(f, delimiter=',')
a.writerows(rows

cursor.close()
You write that row separately

with open('test.csv', 'w', newline= '') as f:
    a = csv.writer(f, delimiter=',')
    a.writerow(["Header 1", "Header 2"])  ## etc
    a.writerows(rows)  ## closing paren added 
thank you that worked