C# and Oracle – 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 C# can be used to export data to a CSV file called ‘personexport.csv’, from an Oracle database table called ‘person’, which was used in the examples for selectinginserting, updating, deleting and importing data (CSV, text, XML and JSON).

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

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-catch-finally’ block is used to catch any errors that may occur, as well as tidy up at the end, regardless of whether the export is successful or not.

// Database connection variable.
OracleConnection connect = new OracleConnection(
    "Data Source=localhost:1521/Demo;" + 
    "User Id=DemoUN; Password=DemoPW");

try
{

    // Connect to database.
    connect.Open();

}
catch (Exception e)
{

    // Confirm unsuccessful connection and stop program execution.
    Console.WriteLine("Database connection unsuccessful.");
    System.Environment.Exit(1);

}

// Export path and file.
string exportPath = @"C:\demo\";
string exportCsv = "personexport.csv";

// Stream writer for CSV file.
StreamWriter csvFile = null;

// Check to see if the file path exists.
if (!Directory.Exists(exportPath))
{

    // Display a message stating file path does not exist.
    Console.WriteLine("File path does not exist.");

    // Stop program execution.
    System.Environment.Exit(1);

}

try
{

    // Query text.
    string sqlText = @"
        SELECT id, firstname, lastname, title, dob 
        FROM person 
        ORDER BY id
    ";

    // Query text incorporated into SQL command.
    OracleCommand sqlSelect = new OracleCommand(sqlText, connect);

    // Execute SQL and place data in a reader object.
    OracleDataReader reader = sqlSelect.ExecuteReader();

    // Stream writer for CSV file.
    csvFile = new StreamWriter(@exportPath + exportCsv);

    // Add the headers to the CSV file.
    csvFile.WriteLine(String.Format("\"{0}\",\"{1}\",\"{2}\"," +
        "\"{3}\",\"{4}\"",
        reader.GetName(0), reader.GetName(1), reader.GetName(2), 
        reader.GetName(3), reader.GetName(4)));

    // Construct CSV file data rows.
    while (reader.Read())
    {

        // Add line from reader object to new CSV file.
        csvFile.WriteLine(String.Format("\"{0}\",\"{1}\",\"{2}\"," +
            "\"{3}\",\"{4}\"",
            reader[0], reader[1], reader[2], reader[3], 
            reader.GetDateTime(4).ToString("dd/MM/yyyy")));

    }

    // Close the file.
    csvFile.Close();

    // Today's date.
    DateTime today = DateTime.Now;

    // Construct the backup file name.
    string exportBackupCsv = exportCsv.Substring(0, exportCsv.Length-4) +
        "-" + (int)today.DayOfWeek + "-" +
        today.DayOfWeek.ToString().ToLower() + ".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 (!File.Exists(Path.Combine(exportPath, exportBackupCsv)) || 
        (File.Exists(Path.Combine(exportPath, exportBackupCsv)) && 
        File.GetLastWriteTime(
            Path.Combine(exportPath, exportBackupCsv)).Date != 
            today.Date))
    {

        // Copy the CSV export.
        File.Copy(Path.Combine(exportPath, exportCsv),
            Path.Combine(exportPath, exportBackupCsv), true);

    }

    // Message stating export successful.
    Console.WriteLine("Data export successful.");

}
catch (Exception e)
{

    // Message stating export unsuccessful.
    Console.WriteLine("Data export unsuccessful.");
    System.Environment.Exit(1);

}
finally
{

    // Close the database connection and CSV file.
    connect.Close();
    csvFile.Close();

}

The CSV file produced contains the following data.

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

Further Resources