Reputation: 65
I want to convert some database data to .csv format. At the beginning, I create a connection with a database then create a cursor instance, send query through that cursor instance, fetch your data & close the connection. My problem is that I can't visualize the headers of the table, I get just the content.
import pyodbc
import csv
connection = pyodbc.connect("Driver={ODBC Driver 11 for SQL Server};"
"Server=*****;"
"Database=****;"
"uid=****;pwd=****")
cursor = connection.cursor()
cursor.execute("Select * from Table")
data=cursor.fetchall()
with open('test.csv', 'w', newline= '') as f:
a = csv.writer(f, delimiter=',')
a.writerows(data)
cursor.close()
connection.close()
Upvotes: 2
Views: 862
Reputation: 31991
use pandas for reading data from db to export into csv
import pandas as pd
sql='Select * from Table'
df= pd.read_sql(sql,sql_connection)
df.to_csv('csv_filename')
Upvotes: 2