简体   繁体   中英

mysql stored procedure bulk insert

I have a stored procedure that looks like that:

InsertItem: INSERT INTO (IN itemId INT, name TEXT);

Is there a way I could execute a bulk of it? like instead of executing something like that:

using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
    connection.Open();
    foreach (Item item in GetItems())
    {
        using (MySqlCommand command = new MySqlCommand("InsertItem", connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@itemId", item.ItemId);
            command.Parameters.AddWithValue("@name", item.Name);
            command.ExecuteNonQuery();
        }
    }
}

I'm trying to achieve code looking like that without successing:

using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
    connection.Open();
    using (MySqlCommandBulk command = new MySqlCommand("InsertItem", connection))
    {
        command.CommandType = CommandType.StoredProcedure;
        for (Item item in GetItems())
        {
            MySqlCommandBulkItem bulkItem = new MySqlCommandBulkItem();
            bulkItem["itemId"] = item.ItemId;
            bulkItem["name"] = item.Name;
            command.BulkItems.Add(bulkItem);
        }
        command.Execute();
    }
}

My point is that the command will send all of the data at once, and will not send each query alone.
Any ideas?

The Oracle connector for the Dotnet framework allows the use of arrays in place of scalars on parameters. But the MySQL connector doesn't.

There are two ways to accelerate bulk loads in MySQL.

One of them applies to InnoDB tables but doesn't help with MyISAM tables. Start a transaction. Then, after every few hundred rows, COMMIT it and start another one. That will commit your table inserts in bunches, which is faster than autocommiting them individually.

The other is to use MySQL's LOAD DATA INFILE command to slurp up a data file and bulk-insert it into the database. This is very fast, but you have to be diligent about formatting your file correctly.

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