c# - 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);
但我不知道如何制作一种方法来处理这个设置
解决方案
您正在为每个插入打开和关闭连接。
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();
}
}
}
推荐阅读
- javascript - 对于大文件,使用 dataURI 创建 iframe 失败,有什么解决方法吗?
- oracle - 使用 Oracle 6i 和批处理数据库更改创建报告
- javascript - 确定数组中的位置
- python - Python计算两列的不同值
- java - docker 基础镜像更改导致 maven 无法正常工作
- python - 如何根据两个值检查两个变量
- javascript - Backgrid.SelectCell.extend 选项值必须是数字吗?
- flask - Authlib - 将授权 url 传递为 json
- c++ - 仅保留重复的值 - Vectors C++
- kubernetes - 使用 Heketi 在 Kubernetes 集群上安装 GlusterFS 时出现问题