How to bulk insert a CSV file into SQLite C#

前端 未结 5 1948
别那么骄傲
别那么骄傲 2020-12-10 06:12

I have seen similar questions (1, 2), but none of them discuss how to insert CSV files into SQLite. About the only thing I could think of doing is to use a CSVDataAdap

5条回答
  •  执笔经年
    2020-12-10 07:01

    Addressing the last part of your question:

    Perhaps somebody knows the much simpler thing: how to do bulk inserts of CSV files into SQLite...

    Given you need to import a few thousand (or a cpl of million) records into sqlite from a CSV file,
    When there is no direct support for csv data import via the select or insert commands,
    And the iterative row by row reading & inserting is not performant
    Then a practical alternative is to use the "sqlite?.exe" & the import command via shell execute from your c# code.

    loadcsvtosqlite.cs

    Process proc = new Process {
        StartInfo = new ProcessStartInfo {
            FileName = @"loadcsvtosqlite.bat",
            Arguments = @"",
            UseShellExecute = true,
            RedirectStandardOutput = false,
            CreateNoWindow = true
        }
    };
    proc.Start();
    proc.WaitForExit();
    

    loadcsvtosqlite.bat

    sqlite3.exe "db name" < loadcsv.sql
    

    loadcsv.sql

    drop table if exists ;
    create table 
    (field1 datatype, field2 datatype ....); .separator "," .import

    提交回复
    热议问题