繁体   English   中英

使用 C# 代码在更短的时间内将批量 CSV 数据插入 SQLite

[英]Insert bulk CSV data into SQLite in less time using c# code

我的 CSV 文件中有 300 万条数据。 我想在 10 -15 分钟内将这些批量数据插入到 SQLite 数据库中。 通常使用以下代码需要 20 分钟。

我的样品:

SQLiteConnection con = new SQLiteConnection("Data Source="D:\\SQLiteData.db;Version=3;New=False;Compress=True;");
        if (!File.Exists("D:\\SQLiteData.db"))
        {
            SQLiteConnection.CreateFile("D:\\SQLiteData.db");
        }
        con.Open();
        SQLiteCommand com = con.CreateCommand();
        com.Transaction = con.BeginTransaction();
        com.CommandText = "CREATE TABLE Sample([ELEMENT_ID] real,[DATE] datetime,[COMMENT] real);"
            com.ExecuteNonQuery();
        com.CommandText = "INSERT INTO [Sample] VALUES(@C0,@C1,@C2)";
        using (var fileStream = new FileStream("E:\\comma.csv", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (StreamReader streamReader = new StreamReader(fileStream))
        {
            using (CsvReader reader = new CsvReader(streamReader))
            {
                reader.ValueSeparator =’,’;
                reader.ReadHeaderRecord();
                while (reader.HasMoreRecords)
                {
                    DataRecord record = reader.ReadDataRecord();
                    com.Parameters.Clear();
                    for (int i = 0; i < reader.HeaderRecord.Count; i++)
                    {
                        com.Parameters.AddWithValue("@c" + i, string.Empty);
                    }
                    com.ExecuteNonQuery();
                }
            }
        }

任何人都可以建议我在更短的时间内将批量 CSV 数据移动到 SQLite 的替代方法吗?

执行一次巨大的插入导致单个 ExecuteNonQuery() 和单个事务应该提高性能。 您也可以尝试通过 processInfo 导入 csv。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM