SQL Bulk Copy by mapping columns dynamically

c# columnmappings sql sqlbulkcopy

Question

I read the file data into dataset and trying to bulk insert using SQL bulk copy by mapping the columns. All my column names in the database are in lower case which is created from my code.

I am not sure why I get "The specified column doesn't exist in the database" exception. Although I see all the columns mapped in the bulk copy object. Please advise.

public static void BatchBulkCopy(DataTable dataTable, string DestinationTbl,  List<string> columnMapping,string filename)
{         
    // Get the DataTable 
    DataTable dtInsertRows = dataTable;

    using (SqlBulkCopy sbc = new SqlBulkCopy(program.connectionStr.ToString()))
    {
        try 
        {
            foreach (DataColumn col in dataTable.Columns)
            {                   
                sbc.ColumnMappings.Add(col.ColumnName.ToLower(), col.ColumnName.ToLower());
                // Console.WriteLine("ok\n");
            }

            sbc.DestinationTableName = DestinationTbl.ToLower();
            sbc.BulkCopyTimeout = 8000;
            sbc.DestinationTableName = "["+ DestinationTbl.ToLower() + "]";
            sbc.WriteToServer(dtInsertRows);
            sbc.Close();
        }

        catch (Exception ex)
        {           

        }      
    }
}

Popular Answer

You haven't open database connection. Insert sbc.Open(); before sbc.WriteToServer(dtInsertRows);




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why