Hi Team,
please help me first time using pandas for extracting sql table with headers into csv file.
how to write below header line to csv.
writer.writerow(col[0] for col in cursor.description)
or any other best way of extracting sql table data with headers. Sep="|" via pandas.
below is my attempted code
please help me first time using pandas for extracting sql table with headers into csv file.
how to write below header line to csv.
writer.writerow(col[0] for col in cursor.description)
or any other best way of extracting sql table data with headers. Sep="|" via pandas.
below is my attempted code
import csv
import pyodbc
import pandas as pd
cursor = connection.cursor()
f = open('output.csv', 'w')
cursor.execute('select * from mydata')
with open("output.csv", "w", newline="") as outfile:
writer = csv.writer(outfile, delimiter="|", quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(col[0] for col in cursor.description)
# Get data in batches
while True:
df = pd.DataFrame(cursor.fetchmany(1000))
if len(df) == 0:
break
else:
df.to_csv(f, index=False, header=False, mode='a',sep="|")
# Clean up
f.close()
cursor.close()
connection.close()
