简体   繁体   English

使用SqlBulkCopy和datatable插入excell记录

[英]Using SqlBulkCopy with datatable to insert excell records

I am trying to use SqlBulkCopy woth the datatable to insert data in to database 我正在尝试使用SqlBulkCopy将数据表插入到数据库中

I have this code 我有这个代码

 string mydemo="my demo record";
        DataTable prodSalesData = new DataTable("ProductSalesData");

        // Create Column 1: SaleDate
        DataColumn dateColumn = new DataColumn();
        dateColumn.DataType = Type.GetType("System.String");
        dateColumn.ColumnName = "SaleDate";

        prodSalesData.Columns.Add(dateColumn);


        DataRow dailyProductSalesRow = prodSalesData.NewRow();
        dailyProductSalesRow["SaleDate"] = mydemo;


        // Create DbDataReader to Data Worksheet
        using (OleDbDataReader dr1 = command1.ExecuteReader())
        {
            // Bulk Copy to SQL Server
            using (SqlBulkCopy bulkCopy1 = new SqlBulkCopy(con))
            {

                bulkCopy1.DestinationTableName = "activity1";
                bulkCopy1.ColumnMappings.Add(0, "id");
                bulkCopy1.ColumnMappings.Add(1,"name");
                bulkCopy1.ColumnMappings.Add(2, "activity1first");
                bulkCopy1.ColumnMappings.Add(3, "activity1second");
                bulkCopy1.ColumnMappings.Add(4, prodSalesData.Columns.ToString());
                bulkCopy1.WriteToServer(dr1);

            }
        }

Here fors 4 recods comes frome xcell file but i want to insert an external data to the same table , i tried this much but it gives me this error 在这里fors 4 recods来自xcell文件,但是我想在同一张表中插入外部数据,我尝试了很多,但是给了我这个错误

The given ColumnMapping does not match up with any column in the source or destination.

Any help? 有什么帮助吗?

Thanks 谢谢

The error is triggered because you are setting the mappinng for 4 prodSalesData columns (by position) but you only have one column. 由于您正在为4个prodSalesData列(按位置)设置mappinng,但是只有一列,因此触发了错误。 The ColumnMappings should contain the columns being mapped from the source to the destination ie ColumnMappings应该包含从源映射到目标的列,即

bulkCopy1.ColumnMappings.Add("SaleDate", prodSalesData.Columns.ToString());

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

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