由于内存问题,我决定将 DataTable 替换/转换为 IDataReader。
经过一段时间的谷歌和 MSDN 搜索,我在http://www.michaelbowersox.com/2011/12/22/using-a-custom-idatareader-to-stream-data-into-a-database遇到了这个/和Bulk Insert Sql Server 数百万条记录。
由于我使用的是 LumenWorks Fast CSV Reader,但我还没有弄清楚如何告诉 CsvReader 让 IDataReader 使用 2 个不同的字段版本。:-( csvReader.FieldCount 是这里的关键,但我不知道如何告诉 CsvReader 使用具有 IDataReader 接口的两个新类中的任何一个。请参阅下面的原始脚本和修改后的脚本......谢谢......
//原始脚本...
var dbConnection = new SqlConnection(_dbConnectionString);
using (var dbBulkCopy = new SqlBulkCopy(dbConnection)
{
using (CsvReader csvReader = new CsvReader(new StreamReader(filePath), false, '|', '"', '\\', '#', ValueTrimmingOptions.UnquoteOnly))
{
while(csvReader.ReadNextRecord())
{
if (csvReader.FieldCount == 48)
{
//Version 1...
dataRow["DealerId"] = csvReader[0];
dataRow["DealerName"] = csvReader[1];
//Etc...
}
else if (csvReader.FieldCount == 51)
{
//Version 2...
dataRow["DealerId"] = csvReader[0];
dataRow["DealerName"] = csvReader[1];
//Etc...
}
else { throw new Exception("Field Total Count Mismatched"); }
dataTable.Rows.Add(dataRow);
}
dbConnection.Open();
dbBulkCopy.WriteToServer(dataTable);
}
}
//新脚本...
var dbConnection = new SqlConnection(_dbConnectionString);
using (var dbBulkCopy = new SqlBulkCopy(dbConnection)
{
dbConnection.Open();
using (CsvReader csvReader = new CsvReader(new StreamReader(filePath), false, '|', '"', '\\', '#', ValueTrimmingOptions.UnquoteOnly))
{
csvReader.ReadNextRecord();
dbBulkCopy.WriteToServer(
if (csvReader.FieldCount == 48)
{
//Version 1...
csvReader....??? //Assign a custom class having IDataTable...
}
else if (csvReader.FieldCount == 51)
{
//Version 2...
csvReader....??? //Assign a custom class having IDataTable...
}
else { throw new Exception("Field Total Count Mismatched"); }
);
}
}
//示例脚本...
using (var file = new StreamReader(path))
using (var csv = new CsvReader(file, true)) // true = has header row
using (var bcp = new SqlBulkCopy(connection)) {
bcp.DestinationTableName = "TableName";
bcp.WriteToServer(csv);
}