Python and SQL Server – Exporting Data (CSV)

Sometimes it can be useful to export data from a database, so that it can be analysed, or, to import in to another computer system. CSV, or Comma Separated Value files, are one such file format that allows for both of these scenarios.

Below is an example of how Python can be used to export data to a CSV file called ‘personexport.csv’, from an SQL Server database table called ‘person’, which was used in the examples for selecting, inserting, updating, deleting and importing data.

Firstly, the CSV file path and name are set and a check is made to see if the path actually exists. If it does, a connection to the database is established and a query is executed to extract the data from the database. The CSV file is then opened for writing and the table headers, along with the rows of data returned are added to it.

A rolling seven day backup is also included. This makes a copy of the CSV file that has just been created, giving it a name that includes the index number for the day of the week, along with the day itself, for example, 'personexport-1-monday.csv', for the backup on a Monday. Here, Sunday is classed as the first day of the week, with an index value of zero. Note that the backup is only done for the first time that this is run in a given day. Backups are then overwritten each week.

Finally, confirmation of a successful export is provided. A ‘try-except-finally’ block is used to catch any errors that may occur, as well as close the database connection, regardless of whether the export is successful or not.

import csv
import datetime
import os
import pyodbc
import shutil

# File path and name.
filePath = 'c:\\demo\\'
fileName = 'personexport.csv'

# Database connection variable.
connect = None

# Check if the file path exists.
if os.path.exists(filePath):


        # Connect to database.
        connect = pyodbc.connect(Driver='SQL Server', host='localhost',
                                 database='Demo', user='DemoUN',

    except pyodbc.Error as e:

        # Confirm unsuccessful connection and stop program execution.
        print("Database connection unsuccessful.")

    # Cursor to execute query.
    cursor = connect.cursor()

    # SQL to select data from the person table.
    sqlSelect = \
        "SELECT id, firstname, lastname, title, dob \
         FROM person \
         ORDER BY id"


        # Execute query.

        # Fetch the data returned.
        results = cursor.fetchall()

        # Extract the table headers.
        headers = [i[0] for i in cursor.description]

        # Open CSV file for writing.
        with open(filePath + fileName, 'w') as csvFile:

            # Create CSV writer.   
            writer = csv.writer(csvFile, delimiter=',', lineterminator='\r',
                                quoting=csv.QUOTE_ALL, escapechar='\\')

            # Add the headers and data to the CSV file.

        # Today's date.
        today =

        # Construct the backup file name.
        fileNameBackup = fileName[0:-4] + "-" + \
                         today.strftime("%w") + "-" + \
                         today.strftime("%A").lower() + ".csv"

        # Check if the backup file does not exist, or if it does, check that
        # today's date is different from the last modified date.
        if not(os.path.isfile(filePath + fileNameBackup)) or \
           (os.path.isfile(filePath + fileNameBackup) and \
           today != + fileNameBackup).st_ctime)):

            # Copy the CSV export.
            shutil.copyfile(filePath + fileName, filePath + fileNameBackup)

        # Message stating export successful.
        print("Data export successful.")

    except pyodbc.Error as e:

        # Message stating export unsuccessful.
        print("Data export unsuccessful.")


        # Close database connection.


    # Message stating file path does not exist.
    print("File path does not exist.")

The CSV file produced contains the following data.