首页 > 解决方案 > C# Mysql Insert Many Rows,性能问题

问题描述

我想知道如何批量插入而不是每次都执行此方法。

当我尝试插入 1000 行时,它变得越来越慢:

queryText = "INSERT INTO `player_items` (`player_id`, `item_id`, `count`) VALUES (@player_id, @item_id, @count)";
for (int i = 0; i < player.invenotrySize; i++)
{
    Item item = player.inventory.GetItem[i];
    MySqlParameter[] parameters = {
         new MySqlParameter("player_id", 1),
         new MySqlParameter("item_id", item.data.id),
         new MySqlParameter("count", item.amount),
    };

    ExecuteNonQuery(queryText, parameters);
}
public int ExecuteNonQuery(string queryText, params MySqlParameter[] parameters)
{
    int affectedRows = 0;
    using (MySqlConnection mySqlConnection = CreateConnection())
    {
        using (MySqlCommand mySqlCommand = new MySqlCommand(queryText, mySqlConnection))
        {
            mySqlCommand.CommandType = CommandType.Text;
            mySqlCommand.Parameters.AddRange(parameters);
            affectedRows = mySqlCommand.ExecuteNonQuery();
        }
    }

    return affectedRows;
}

我认为最佳方法是将所有内容插入一个巨大的行。例如

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

但我不知道如何制作一种方法来处理这个设置

标签: c#mysql

解决方案


您正在为每个插入打开和关闭连接。

using (MySqlConnection mySqlConnection = CreateConnection())

这是一个非常昂贵的过程,因此不是真正使用数据库的方式。

您应该只打开一次连接,然后在完成后关闭它。根据您的应用程序所做的事情,这可能是在您启动应用程序时(或在您执行第一个数据库查询之前),然后在退出应用程序时关闭它(或在您确定将不再有数据库查询之后。

那么理想情况下,您还应该重用 SqlCommand 实例。但是您需要确保清除两者之间的参数。那么你有这样的东西

int affectedRows = 0;
using (MySqlConnection mySqlConnection = CreateConnection())
{
    string queryText = "INSERT INTO `player_items` (`player_id`, `item_id`, `count`) VALUES (@player_id, @item_id, @count)";
    using (MySqlCommand mySqlCommand = new MySqlCommand(queryText, mySqlConnection))
    {
        mySqlCommand.CommandType = CommandType.Text;
        for (int i = 0; i < player.invenotrySize; i++)
        {
            Item item = player.inventory.GetItem[i];
                MySqlParameter[] parameters = {
                    new MySqlParameter("player_id", 1),
                    new MySqlParameter("item_id", item.data.id),
                    new MySqlParameter("count", item.amount)};

                mySqlCommand.Parameters.Clear();
                mySqlCommand.Parameters.AddRange(parameters);
                affectedRows += mySqlCommand.ExecuteNonQuery();
        }
    }
}

推荐阅读