[英]Importing CSV to SQL-Server - Performance
我創建了一個小項目,該項目允許用戶通過Entity-Framework將CSV文件導入SQL。 主要過程如下所示:
using (TextFieldParser tx = new TextFieldParser(file, Encoding.UTF8))
{
tx.TextFieldType = FieldType.Delimited;
tx.SetDelimiters(";");
tx.ReadLine(); //The First Line are the headers, no need
while (!tx.EndOfData)
{
decimal decTmp;
int intTmp;
string[] fields = tx.ReadFields();
//Convert every field to the appropriate type, tryparse if nullable
ReportInfo("Verarbeite Nummer: " + fields[(int)ConnectionEvaluationFileField.PhoneNumber].Trim());
Verbindunganalyse con = new Verbindunganalyse();
con.Auswertungszeitraum = fields[(int)ConnectionEvaluationFileField.EvaluationTimeSpan].TrimStart('0');
con.Betrag_inkl_MWST_CHF = Decimal.Parse(fields[(int)ConnectionEvaluationFileField.Cost]);
if (decimal.TryParse(fields[(int)ConnectionEvaluationFileField.DataInMb], out decTmp))
con.Daten_MB = decTmp;
con.Durchwahlnummer = Int64.Parse(fields[(int)ConnectionEvaluationFileField.PhoneNumber]);
con.Produkteigenschaft = fields[(int)ConnectionEvaluationFileField.ProductProperty];
if (Int32.TryParse(fields[(int)ConnectionEvaluationFileField.Messages], out intTmp))
con.SMS_MMS_Anzahl = intTmp;
con.TelefonieDauer = TimeSpan.Parse(fields[(int)ConnectionEvaluationFileField.CallLength]);
con.Untergruppe = fields[(int)ConnectionEvaluationFileField.SubGroup];
if (Int32.TryParse(fields[(int)ConnectionEvaluationFileField.Connections], out intTmp))
con.Verbindungen_Anzahl = intTmp;
container.Verbindunganalyse.Add(con);
}
}
它是德語,但是我認為代碼非常清楚:我使用TextFieldParser讀取了數據,創建了一個新的Entitiy並將其解析/檢查到屬性中。
問題:客戶以前有一個訪問解決方案,需要20-30秒才能導入數據,而對於我的解決方案,我需要2-3分鍾才能處理2個文件和5k數據集。
我找到了一些BulkInsert,例如https://efbulkinsert.codeplex.com/ ,但是我們在這里談論的是兩個文件中的10k數據集。
我刪除了ReportInfo等。但是,我看不到一種使這項工作更快的方法。 您是否認為使用EF可以更快地制作此類作品? 還是TextFieldParser只是很慢,我需要在那里檢查?
我知道這是一篇舊文章,但我自己一直在嘗試。 我使用以下代碼嘗試了Entity Framework Seeder NuGet程序包和裸機SQL批量插入 。
CREATE TABLE [dbo].[TempTable] (
[Field] type constraints,
etc...
)
GO
BULK INSERT TempTable FROM 'filePath' WITH (
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\r\n'
)
GO
INSERT INTO [FinalTable] SELECT [Fields] FROM [TempTable]
GO
DROP TABLE [TempTable]
seeder方法在67秒內插入10,000條記錄,而批量插入方法則需要223 ms。 真是輕而易舉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.