Created
July 29, 2015 17:01
-
-
Save mbiette/91f4199795fef0de2e29 to your computer and use it in GitHub Desktop.
C# Script to dump a CSV to an Oracle Database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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