使用MySqlCommand在一个查询中执行多个INSERT

本文关键字:查询 执行 INSERT 一个 MySqlCommand 使用 | 更新日期: 2023-09-27 18:00:37

我正在使用以下代码:

        string cmd = "INSERT INTO " + Tables.Lux() + " VALUES(NULL, @Position, @Mode, @Timer)";
        try
        {
            using (var MyConnection = new MySqlConnection(ConfigurationManager.ConnectionStrings["DataFormConnection"].ConnectionString))
            {
                using (MySqlCommand command = new MySqlCommand(cmd, MyConnection))
                {
                    MyConnection.Open();
                    command.Parameters.Add(new MySqlParameter("Position", Element.Position));
                    command.Parameters.Add(new MySqlParameter("Mode", Element.Mode));
                    command.Parameters.Add(new MySqlParameter("Timer", Element.Timer));
                    command.ExecuteNonQuery();
                }
            }
        }

我正在使用上面的代码插入包含100个项目的Element列表中的数据。我只想在一个查询中添加100个值,我知道SQL语句看起来像:

INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);

但我不知道如何使用CCD_ 1方法来应用该结构。

我的目标是传递这个函数List<Element>,而不仅仅是Element,并创建一个INSERT语句,其中包含列表中的所有项,只在一个查询中执行。请帮忙吗?

谢谢。

使用MySqlCommand在一个查询中执行多个INSERT

这样试试:

string cmd = "INSERT INTO " + Tables.Lux() + " VALUES ";
int counter = 0;
foreach (Element e in list) 
{
    sql += "(NULL, @Position" + counter + ", @Mode" + counter + ", @Timer" + counter + "),";
    command.Parameters.Add(new MySqlParameter("Position" + counter, e.Position));
    command.Parameters.Add(new MySqlParameter("Mode" + counter, e.Mode));
    command.Parameters.Add(new MySqlParameter("Timer" + counter, e.Timer));
    counter++;
}
command.CommandText = sql.Substring(0, sql.Length-1); //Remove ',' at the end

通过这种方式,您可以在查询中拥有可变数量的参数,并且您只需要对数据库触发一次,而不是n次

这是未经测试的,我简直想不到!

我使用@异种生成答案来解决我的问题,也许可以帮助其他人

List<EntregadorRPC.Address> addresstoinsert = eoSendAddressList.addresses;
int      batteryLvl = eoSendAddressList.batteryLevel;
DateTime dtHoraLocal;
int      size = addresstoinsert.Count;
const string insertHeader = "Insert into historicolocalizacao (Provedor, CodUsuario, Latitude, Longitude, Precisao, Logradouro, " +
                            "Complemento, Setor, Cidade, UF, Cep, DataHoraLocal, bateria) Values";
StringBuilder insertValues = new StringBuilder("");
using (MySqlCommand cmd = new MySqlCommand()) {
    for (int i = 0; i < size; i++) {
        EntregadorRPC.Address address = addresstoinsert[i];
        dtHoraLocal = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        dtHoraLocal = dtHoraLocal.AddMilliseconds(address.dataHoraLocal).ToLocalTime();
        /*address.logradouro       = WSUtils.RemoveSpecialCharacters(address.logradouro);
        address.formattedAddress = WSUtils.RemoveSpecialCharacters(address.formattedAddress);*/
        cmd.Parameters.AddWithValue($"@provedor{i}",      address.provedor);
        cmd.Parameters.AddWithValue($"@user_id{i}",       user.user_id);
        cmd.Parameters.AddWithValue($"@latitude{i}",      address.latitude);
        cmd.Parameters.AddWithValue($"@longitude{i}",     address.longitude);
        cmd.Parameters.AddWithValue($"@precisao{i}",      address.precisao);
        cmd.Parameters.AddWithValue($"@logradouro{i}",    address.logradouro);
        cmd.Parameters.AddWithValue($"@complemento{i}",   address.complemento);
        cmd.Parameters.AddWithValue($"@setor{i}",         address.setor);
        cmd.Parameters.AddWithValue($"@cidade{i}",        address.cidade);
        cmd.Parameters.AddWithValue($"@uf{i}",            address.uf);
        cmd.Parameters.AddWithValue($"@cep{i}",           address.cep);
        cmd.Parameters.AddWithValue($"@datahoralocal{i}", dtHoraLocal.ToString("yyyy-MM-dd HH:mm:ss"));
        cmd.Parameters.AddWithValue($"@bateria{i}",       batteryLvl);
        insertValues.Append($"(@provedor{i}, @user_id{i}, @latitude{i}, @longitude{i}, @precisao{i}, @logradouro{i}, @complemento{i}, @setor{i}, @cidade{i}, @uf{i}, @cep{i}, @datahoralocal{i}, @bateria{i})");
        if (i < size - 1) {
            insertValues.Append(",");
        }
    }
    cmd.Connection  = conn;
    cmd.CommandText = $"{insertHeader}{insertValues}";
    await cmd.ExecuteNonQueryAsync();
}