5

我正在使用以下代码:

        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语句,其中包含列表中的所有项目,仅在一个查询中执行。请问有什么帮助吗?

谢谢你。

4

2 回答 2

9

试试这样:

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 次

这是未经测试的,只是在我的脑海中!

于 2015-06-30T11:23:56.133 回答
-1

我用@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();
}
于 2020-10-30T22:42:41.950 回答