2

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()

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.