Python and Oracle – Exporting Data (Text)

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. Text files are one such file format that allows for both of these scenarios. These text files are often called delimited text files because each piece of data is separated by a delimiter.

Below is an example of how Python can be used to export data to a text file called ‘personexport.txt', from an Oracle database table called ‘person’, which was used in the examples for selecting, inserting, updating, deleting and importing data. The delimiter used to separate each piece of data in this example is the pipe (|) symbol.

Firstly, the text 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 text file is then opened for writing and the table headers are added to it, followed by the rows of data.

A rolling seven day backup is also included. This makes a copy of the text 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.txt', 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-catch-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 oracledb
import os
import shutil

# File path and name.
filePath = '/home/demouser/Documents/'
fileName = 'personexport.txt'

# Database connection variable.
connect = None

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

    try:

        # Connect to database.
        connect = oracledb.connect('DemoUN/DemoPW@localhost:1521/freepdb1')

    except oracledb.Error as e:

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

    # 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"""

    try:

        # Execute query.
        cursor.execute(sqlSelect)

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

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

        # Open text file for writing.
        textFile = csv.writer(open(filePath + fileName, 'w', newline=''),
                              delimiter='|', lineterminator='\r\n',
                              quoting=csv.QUOTE_NONE, escapechar='\\')

        # Add the headers and data to the text file.
        textFile.writerow(headers)
        textFile.writerows(results)

        # Today's date.
        today = datetime.datetime.now().date()

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

        # 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 != datetime.date.fromtimestamp(os.stat(filePath + fileNameBackup).st_ctime)):

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

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

    except oracledb.Error as e:

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

    finally:

        # Close the cursor and database connection.
        cursor.close()
        connect.close()

else:

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

The text file produced contains the following data.

ID|FIRSTNAME|LASTNAME|TITLE|DOB
1|Bob|Smith|Mr|1980-01-20 00:00:00
3|Fred|Bloggs|Mr|1975-05-07 00:00:00
4|Alan|White|Mr|1989-03-20 00:00:00
5|Fiona|Bloggs|Mrs|1985-05-19 00:00:00
6|Zoe|Davis|Miss|1979-07-11 00:00:00
7|Tom|Ingram|Mr|1971-10-04 00:00:00
8|Karen|Thomas|Mrs|1969-03-08 00:00:00
9|Samantha|Yates|Miss|1995-08-27 00:00:00

More