How to use SQL against a CSV file

后端 未结 5 1934
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 11:04

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#?

相关标签:
5条回答
  • 2021-01-12 11:14

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

    Textfile Connection String Samples

    0 讨论(0)
  • 2021-01-12 11:22

    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
    }
    
    0 讨论(0)
  • 2021-01-12 11:26

    So, do you mean using Linq?

    Something like one of these?
    http://blogs.msdn.com/b/wriju/archive/2009/05/24/linq-to-csv-getting-data-the-way-you-want.aspx
    http://blogs.msdn.com/b/ericwhite/archive/2008/09/30/linq-to-text-and-linq-to-csv.aspx

    0 讨论(0)
  • 2021-01-12 11:27
    // 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;}
    }
    
    0 讨论(0)
  • 2021-01-12 11:32

    You can use Openrowsets .

    Enable SQL Ad Hoc/Openrowset in SQL configuration first. Once enabled you'll be able to connect your SQL Server Managerment studio and query Excel and comma delimited files.

    Your queries will look something like:

    SELECT * FROM OPENROWSET('MSDASQL','Driver={Microsoft Text Driver (*.txt; *.csv)};DefaultDir={your path}','SELECT * FROM ypurtextfile.csv')
    

    You can use these queries in your C# code just like you query any other tables. Just check with your manager that he's ok with you enabling ad hoc on the SQL Server

    0 讨论(0)
提交回复
热议问题