Fill bank by expanding a given value on so many items

Asked

Viewed 35 times

0

I have in the bank the registration of the building, with the number of rooms qtdSala, among others. I am trying to insert, in another grid, each room according to the value entered in the qtdSala, to register on the table rooms, through a for, so I tried so:

private void CriarSalas(int nSalas)
{
    for (int i = 0; 1 < nSalas; i++)
    {

        try
        {
            SqlConnection con = new SqlConnection(conexaoString);

            SqlCommand cmd = new SqlCommand(@"INSERT INTO salas
                     (nomeSala)
                VALUES
                     (@nomeSala)", con);

            cmd.Parameters.AddWithValue("@nomeSala", i);

            con.Open();
            cmd.ExecuteNonQuery();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            //Atualiza Grid
            this.salasTableAdapter.Fill(this.bdDataSet.salas);

            SqlConnection con = new SqlConnection(conexaoString);
            con.Close();
            con.Dispose();
        }

    }
}

It doesn’t work, I’m not sure how to reference the nsalas...

He must take the qtdsalas, 20 for example, and create sala01, sala02...until sala20. Following is the model of the table:

TABELA SALAS
____________________________
| Id | IdPredio | NomeSala |
| 23 |       05 | "Sala01" |
| 24 |       05 | "Sala02" |
| 25 |       05 | "Sala03" |
| 26 |       05 | "Sala04" |

1 answer

0


There are several points to consider, follow the refactored code:

// tenha nomes de variaveis/parametros o mais claro possivel
private void CriarSalas(int idPredio, int quantidade) 
{
    try
    {
        // Cria a abre uma conexão no inicio do processo
        // Abrir e fechar conexão possui alto custo de processamento
        // Então abre-se no inicio do processo - loop - e encerra apenas no fim
        var con = new SqlConnection(conexaoString);
        con.Open();

        // para i igual a zero; enquanto i for menor que quantidade; incrementa +1
        for (int i = 0; i < quantidade; i++)
        {
            // Reduza a quantidade de tráfego entre sua aplicação e o banco de dados.
            // Lembre-se, cada caracter possui pelo menos 16-bits de tamanho ou 2-bytes.
            var cmd = new SqlCommand(
                @"INSERT INTO salas(idPredio, nomeSala)VALUES(@idPredio,@nomeSala)", con);

            cmd.Parameters.AddWithValue("@idPredio", idPredio);
            cmd.Parameters.AddWithValue("@nomeSala", $"Sala0{i}");

            cmd.ExecuteNonQuery();    
        }
    }
    catch (Exception ex)
    {
        // Se houver error, exibe a mensagem do erro
        MessageBox.Show($"Erro ao tentar criar sala: {ex.Message}");
    }
    finally
    {
        // Isso deveria ser feito em outro método.
        // Cada método, classe, deve ter responsabilidade unica
        // Esse método deve apenas criar salas, crie outro para atualizar o grid. 
        // Atualiza Grid, porém isso deveria ser feito em outro método.
        //this.salasTableAdapter.Fill(this.bdDataSet.salas);

        // Ao terminar, encerra a conexão    
        con.Close();
        con.Dispose();
    }
}
  • beauty, I liked the tips of good practice, I will follow. But I still have a question: Qdo I say that the amount will be the value of qtdSalas? I do a Where on Insert and then set the amount = qtdSalas.value? or just send amount receive Qtd rooms?

  • Edit your question by adding as is the structure of table rooms. Because I didn’t understand your question.

  • Hey, sorry I’m late, I was just doing a little code work. The table rooms will receive the predials, where has the qtySalas, so in the tables rooms will appear the name of the building and sala01, sala02.... only that the rooms should be listed in a single column, what I do not know, in the same idPredio will have as many rooms as they are in the quantity qtdSalas. Could I clarify? I think I have to relate the quantity to the qtdSalas but I don’t know how....

  • I edited my answer, see if now answers.

  • I also changed the code comments. :)

  • cmd.Parameters.Addwithvalue("@nameSala", $"Sala0{i}"); I think that’s it, that I didn’t know how to write, I’ll test it and I’ll tell you. Thank you.

  • If it works, please evaluate the answer! :)

  • Man, that work gave me to make it work.... but your answer was what helped!! Thank you very much.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.