Skip to content

Instantly share code, notes, and snippets.

@mbiette
Created July 29, 2015 17:01
Show Gist options
  • Save mbiette/91f4199795fef0de2e29 to your computer and use it in GitHub Desktop.
Save mbiette/91f4199795fef0de2e29 to your computer and use it in GitHub Desktop.
C# Script to dump a CSV to an Oracle Database
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client;
using Microsoft.VisualBasic.FileIO;
namespace CSVToOracle
{
class Program
{
static void Main(string[] args)
{
var source = "MyCSV";
var pathToCSV = @"C:\Users\Maxime.Biette\Desktop\"+source+".csv";
var con = new OracleConnection
{
ConnectionString = "Data Source=server/schema;User ID=user;Password=pass;"
};
con.Open();
var command = con.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
Console.WriteLine("Parsing CSV: " + pathToCSV);
using (TextFieldParser parser = new TextFieldParser(pathToCSV))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
// Building the query
var headers = parser.ReadFields();
var query = new StringBuilder();
query.Append("INSERT INTO MY_TABLE (");
query.Append("SOURCE");
foreach (string field in headers)
{
query.Append(",");
query.Append(field.Replace(" ", "_"));
}
query.Append(") VALUES (");
query.Append(":SOURCE");
foreach (string field in headers)
{
query.Append(",");
query.Append(":"+field.Replace(" ", "_"));
}
query.Append(")");
command.CommandText = query.ToString();
// run the query with params.
while (!parser.EndOfData)
{
command.Parameters.Clear();
command.Parameters.Add("SOURCE",source);
var fields = parser.ReadFields();
for (int i = 0; i < headers.Length; i++ )
{
command.Parameters.Add(headers[i].Replace(" ", "_"), fields[i]);
}
Console.Out.Write(".");
Console.Out.Flush();
command.ExecuteNonQuery();
}
}
con.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment