Home » c# » How to insert multiple rows of a datatable into a table in database at once using mysql,c#

How to insert multiple rows of a datatable into a table in database at once using mysql,c#

Posted by: admin February 21, 2020 Leave a comment

Questions:

How to insert multiple rows of a datatable into a table in database at once using MySQL, in C#

string connectionString = GetConnectionString();
using(var bulkCopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity)) {
     foreach(DataColumn col in dataTable.Columns) {
      bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
     }

     bulkCopy.BulkCopyTimeout = 600;
     bulkCopy.DestinationTableName = destinationTableName;
     bulkCopy.WriteToServer(dataTable);
}

I tried this but getting error-login failed for user ‘testuser‘.This is the db credential

How to&Answers:

SqlBulkCopy is for Microsoft SQL Server, and Oracle’s MySQL Connector/NET doesn’t have any bulk copy functionality. MySqlConnector is an alternative MySQL driver for .NET that does support bulk copy (in MySqlBulkCopy) in the latest beta version, as per this documentation.

You will first need to uninstall MySql.Data, then install MySqlConnector. It uses the same class names, so it should be a drop-in upgrade.

string connectionString = GetConnectionString();
using (var connection = new MySqlConnection(connectionString))
{
    await connection.OpenAsync();

    using (var bulkCopy = new MySqlBulkCopy(connection)
    {
        // ColumnMappings isn't current supported, but they will be inferred automatically
        bulkCopy.DestinationTableName = destinationTableName;
        await bulkCopy.WriteToServerAsync(dataTable);
    }
}