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

时间:2015-06-30 11:11:46

标签: c# mysql sql sqlparameters sql-parametrized-query

我使用以下代码:

        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);

但我不知道如何使用MySqlCommand.Parameters方法应用该结构。

我的目标是传递此函数List<Element>而不仅仅是Element并创建一个INSERT语句,列表中的所有项目只能在一个查询中执行。有什么帮助吗?

谢谢。

2 个答案:

答案 0 :(得分:5)

试试这样:

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次

这是未经考验的,只是出于我的想法!

答案 1 :(得分:0)

我用@xenogenesis答案解决了我的问题,也许可以帮助别人

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();
}