How to use SQL against a CSV file

You can use ODBC to run a query against a CSV File :

// using System.Data.Odbc;

string strConn = @"Driver={Microsoft Text Driver (*.txt; *.csv)};" +
    "Dbq=C:;Extensions=csv,txt";

OdbcConnection objCSV = new OdbcConnection(strConn);
objCSV.Open();

OdbcCommand oCmd = new OdbcCommand("select column1,column2 " +
    "from THECSVFILE.CSV", objCSV);
OdbcDataReader oDR = oCmd.ExecuteReader();

while (oDR.Read())
{
    // Do something
}

You can use the appropriate OLE DB provider to query the text file. You can find the query string here:

Textfile Connection String Samples


// need to add
// using System.Linq;

void Main()
{
    var path = @"C:\myfile.csv";
    string csv = System.IO.File.ReadAllText( path );
    var array = csv.Split(new[]{","}, StringSplitOptions.RemoveEmptyEntries);
    // Do the mapping with your databinding object
    var personArray = array.Select(p => new Person { Name = p}); 
   // You need to have this DataContext defined somewhere, for instance using LinqToSql
    using(var context = new PersonDataContext()){ 
        context.InsertAllOnSubmit(personArray);
        context.SubmitChanges();
    } 
}

// Imagine this class is one of linqToSql class
public class Person{
    public string Name {get;set;}
}

Tags:

C#

Sql

Csv