I am trying to figure out why when I export a database view from a MSSQL database it results in a csv file which only contains the view's header columns. For example, that is the resulting file that I am currently getting:
"",""
"RIG ID","Date - Rig"
"RIG ID","Date - Rig"
"RIG ID","Date - Rig"
...
That is the export code that I am running:
import csv
import os
import pyodbc
# Rig db Params/Vars
# Rigs data csv file path and name.
filePath = os.getcwd() + '/'
fileName = 'export.csv'
...
# SQL to select data from the rigs table.
rigs_export_sql = "SELECT TOP 10 'RIG ID', 'Date - Rig' FROM schema_name.view_name"
def export_rigs_data():
# Database connection variable.
connect = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' +
server+';DATABASE='+database+';UID='+username+';PWD=' + password)
# Cursor to execute query.
cursor = connect.cursor()
# Execute query.
cursor.execute(rigs_export_sql)
# Fetch the data returned.
results = cursor.fetchall()
# Extract the table headers.
headers = [i[0] for i in cursor.description]
# Open CSV file for writing.
csvFile = csv.writer(open(filePath + fileName, 'w', newline=''),
delimiter=',', lineterminator='
',
quoting=csv.QUOTE_ALL, escapechar='\')
# Add the headers and data to the CSV file.
csvFile.writerow(headers)
csvFile.writerows(results)
if __name__ == "__main__":
export_rigs_data()
What I am missing?
Note: when I execute the the following query "SELECT TOP 10 * FROM schema_name.view_name
I am getting all of the data and header fine
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…