简体   繁体   中英

Adding data from a DataTable to a SQL database

After doing some research I found the code below.. I would like to know what I am doing wrong as the code is failing at the line marked with the three stars. I want to copy all the data to a table called api_ReportData on the SQL server.

When trying this, I get the following error: Cannot find destination table.

This is my code:

DataTable api_ReportData = CreateDataTable();

string sqlConnectionString =
    "Server = 10.72.8.196; Database = datastaoge; User Id = sa; Password = Passw0rd";

// Copy the DataTable to SQL Server
using (SqlConnection dbConnection = new SqlConnection(sqlConnectionString))
{
    dbConnection.Open();

    using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
    {
        *** s.DestinationTableName = Aapi_ReportData.TableName;

        foreach (var column in Adapi_ReportData.Columns)
            s.ColumnMappings.Add(column.ToString(), column.ToString());

        s.WriteToServer(api_ReportData);
    }
} 

The meaning of your error is :

The destination table with name return by Aapi_ReportData.TableName does not exist in your destination database.

if your source and destination table has same schema you do not need to use s.ColumnMappings.Add

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