简体   繁体   中英

Using SqlBulkCopy with datatable to insert excell records

I am trying to use SqlBulkCopy woth the datatable to insert data in to database

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

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. The ColumnMappings should contain the columns being mapped from the source to the destination ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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