Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SQL against a CSV file

Tags:

c#

sql

csv

I would like to use a SQL query on a CSV file using C#. There is something like this for java here. Is there anything like this for c#?

like image 890
Luke101 Avatar asked May 16 '12 18:05

Luke101


People also ask

Can you use SQL on a CSV?

You can read, update, delete CSV records with SQL-like query. You can also execute multiple operations sequentially in managed transactions by passing a procedure or using the interactive shell. In the multiple operations, you can use variables, cursors, temporary tables, and other features.


2 Answers

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
}
like image 154
aleroot Avatar answered Oct 05 '22 20:10

aleroot


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

Textfile Connection String Samples

like image 40
Justin Niessner Avatar answered Oct 05 '22 20:10

Justin Niessner