0
以下asp.net代碼從CSV文件中提取數據並將其插入到SQL Server 2005表中。從CSV文件導出數據到SQL Server 2005
但是,我需要指定表名,其數據將被提取的字段名稱,以及靜態代碼中的映射信息(CSV'列名稱和'表格列名稱之間的映射)。
我如何修改下面的代碼,以便它適用於任何表名。
總之,表名和映射應該被動態處理。
public class CsvBulkCopyDataIntoSqlServer
{
protected const string _truncateLiveTableCommandText = @"TRUNCATE TABLE Account";
protected const int _batchSize = 100000;
static void Main(string[] args)
{
LoadCsvDataIntoSqlServer();
}
public static void LoadCsvDataIntoSqlServer()
{
// This should be the full path
var fileName = @"D:\output.csv";
var createdCount = 0;
using (var textFieldParser = new TextFieldParser(fileName))
{
textFieldParser.TextFieldType = FieldType.Delimited;
textFieldParser.Delimiters = new[] { "," };
textFieldParser.HasFieldsEnclosedInQuotes = true;
// var connectionString = ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString;
string connectionString = "Data Source= 172.25.10.4" + ";Initial Catalog= SFdata" + ";Persist Security Info=True;User ID= sa" + ";Password= [email protected]";
var dataTable = new DataTable("Account");
// Add the columns in the temp table
dataTable.Columns.Add("Name");
dataTable.Columns.Add("shippingstreet");
dataTable.Columns.Add("shippingpostalcode");
dataTable.Columns.Add("ShippingCountry");
dataTable.Columns.Add("shippingstate");
//dataTable.Columns.Add("LastName");
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
// Truncate the live table
using (var sqlCommand = new SqlCommand(_truncateLiveTableCommandText, sqlConnection))
{
sqlCommand.ExecuteNonQuery();
}
// Create the bulk copy object
var sqlBulkCopy = new SqlBulkCopy(sqlConnection)
{
DestinationTableName = "Account"
};
// Setup the column mappings, anything ommitted is skipped
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("shippingstreet", "shippingstreet");
sqlBulkCopy.ColumnMappings.Add("shippingpostalcode", "shippingpostalcode");
sqlBulkCopy.ColumnMappings.Add("ShippingCountry", "ShippingCountry");
sqlBulkCopy.ColumnMappings.Add("shippingstate", "shippingstate");
// Loop through the CSV and load each set of 100,000 records into a DataTable
// Then send it to the LiveTable
while (!textFieldParser.EndOfData)
{
dataTable.Rows.Add(textFieldParser.ReadFields());
createdCount++;
if (createdCount % _batchSize == 0)
{
InsertDataTable(sqlBulkCopy, sqlConnection, dataTable);
break;
}
}
InsertDataTable(sqlBulkCopy, sqlConnection, dataTable);
sqlConnection.Close();
}
}
}
protected static void InsertDataTable(SqlBulkCopy sqlBulkCopy, SqlConnection sqlConnection, DataTable dataTable)
{
sqlBulkCopy.WriteToServer(dataTable);
dataTable.Rows.Clear();
}
}
SQL Server集成服務都有一套上用戶必須選擇UI屏幕。而我所有的數據傳輸應該在後臺完成,所以請通過修改上面的代碼來幫助我。 – Peace