简体   繁体   中英

"The given ColumnMapping does not match up with any column in the source or destination" when uploading csv to sql server

I am trying to upload CSV to SQL server by transforming the CSV to Datatable then this Datatable to be inserted into SQL data server. The CSV is read correctly into Datatable but while inserting the data to SQL this error occurs

"The given Column Mapping does not match up with any column in the source or destination"

Here is my code:

static void InsertDataIntoSQLServerUsingSQLBulkCopy(DataTable csvFileData)
    {
        System.IO.File.Create("C:\\Users\\Rana\\Desktop\\inside.txt");
        using (SqlConnection dbConnection = new SqlConnection("Data Source=DESKTOP-N7OIK1O\\MSSQLSERVER02;Initial Catalog=nokia_Alarm;Integrated Security=SSPI;"))
        {
            System.IO.File.Create("C:\\Users\\Rana\\Desktop\\inside1.txt");
            dbConnection.Open();
            using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
            {
                System.IO.File.Create("C:\\Users\\Rana\\Desktop\\inside2.txt");
                s.DestinationTableName = "csv_Table";

                foreach (var column in csvFileData.Columns)
                    s.ColumnMappings.Add(column.ToString(), column.ToString());
                s.WriteToServer(csvFileData);
                System.IO.File.Create("C:\\Users\\Rana\\Desktop\\inside4.txt");
            }
        }
    }

I do not know where the problem is ?

is it in the DB connection ?

(SqlConnection dbConnection = new SqlConnection("Data Source=DESKTOP-N7OIK1O\\MSSQLSERVER02;Initial Catalog=nokia_Alarm;Integrated Security=SSPI)

Should be:

foreach (DataColumn column in csvFileData.Columns)
                    s.ColumnMappings.Add(column.ColumnName, column.ColumnName);

DataTables and most of the ADO.NET types predate generic collections, so when foreach -ing its collections (like DataTable.Columns) you have to provide target type in the foreach to access its properties and methods.

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