Mapping columns in a DataTable to a SQL table with SqlBulkCopy

こ雲淡風輕ζ 提交于 2019-11-26 11:09:25

问题


I would like to know how I can map columns in a database table to the datatable in c# before adding the data to the database.

using (SqlBulkCopy s = new SqlBulkCopy(conn))
{
    s.DestinationTableName = destination;
    s.WriteToServer(Ads_api_ReportData);
}

回答1:


You probably need some thing like

 public void BatchBulkCopy(DataTable dataTable, string DestinationTbl, int batchSize)
{
    // Get the DataTable 
    DataTable dtInsertRows = dataTable;

    using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))
    {
        sbc.DestinationTableName = DestinationTbl;

        // Number of records to be processed in one go
        sbc.BatchSize = batchSize;

        // Add your column mappings here
        sbc.ColumnMappings.Add("field1","field3");
        sbc.ColumnMappings.Add("foo","bar");

        // Finally write to server
        sbc.WriteToServer(dtInsertRows);
    }    
}

Ref: How to use SqlBulkCopyColumnMappingCollection? . .

Seel also http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy




回答2:


This became such a common task that I wrote this helper for it:

public static void AutoMapColumns(SqlBulkCopy sbc, DataTable dt)
{
    foreach (DataColumn column in dt.Columns)
    {
        sbc.ColumnMappings.Add(column.ColumnName, column.ColumnName);
    }
}

Since I was creating the DataTable myself, I named its columns the same as the SQL table.




回答3:


It might be useful to know that if the columns in the source query (or table) and the target table have the same name and are in the exact same order, then there is no need to write out the mappings explicitly, because SqlBulkCopy will create a default mapping with this default order.




回答4:


Use the ColumnMappings:

s.ColumnMappings.Add("Name", "Name");
s.ColumnMappings.Add("Address", "Address");



回答5:


The method Add on ColumnMappings collection allows you to map your columns from source table to destination table. The method ColumnMappings.Add accepts four different ways to map your columns.

SQLBulkCopy is very much strict on data type of both the columns which you have to consider while adding it to ColumnMappings collection



来源:https://stackoverflow.com/questions/17469349/mapping-columns-in-a-datatable-to-a-sql-table-with-sqlbulkcopy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!