Batch INSERT c #

1

I would like to know if it is possible and how to perform an INSERT in the database of 10 equal values and adding 1 more in a field ..

ex: I have a patrimony system and I need to register 10 equal items. when marking a checkbox and adding the amount of items in a textbox it adds the 10 items to the database ...

I need to add a +1 to the number of the tag that is being recorded when writing it.

ex:

txtPlaqueta.Text = "123"
CheckBox = true;
txtValorRepetir = "10" 

so I would stay in bd so

123,124,125,126,127,128,129,130,131,132

If I change the plate number to "50" it would be in bd

50,51,52,53,54,55,56,57,58,59

private void btAdd_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(//string de conexao);

        txtValor.Text = (int.Parse(txtValor.Text) + 1).ToString();

        string inserir = @"INSERT INTO DadosNome (Nome, Valor, Teste, Deletar) Values ('"+txtNome.Text+"', '"+txtValor.Text+"', '"+txtTeste.Text+"', '"+txtDeletar.Text+ "'),('" + txtNome.Text + "', '" + txtValor.Text + "', '" + txtTeste.Text + "', '" + txtDeletar.Text + "')";
        SqlCommand cmd = new SqlCommand(inserir, con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

Assuming that the value column has value "22" when doing the insert would be (22,23,24,25) four records in bd.

    
asked by anonymous 26.02.2018 / 01:38

1 answer

1

There are several problems in your code, but I will focus on the loop, and although with a practice not recommended (concatenate the query string) I will show an example of how your question would be with the code you have: >

    SqlConnection con = new SqlConnection(//string de conexao);


    int inicio = 22; //número do patrimonio inicial
    int quantidade = 10; //quantidade de números que serão inseridos

    string sqlInsert = @"INSERT INTO DadosNome (Nome, Valor, Teste, Deletar) Values ";

    for (int i = 0; i <= quantidade; i++)
    {
          sqlInsert += "('"+txtNome.Text+"', '"+ (inicio + i)  +"', '"+txtTeste.Text+"', '"+txtDeletar.Text+ "'),"; //vai concatenando a sintaxe dos values
    }

    sqlInsert = sqlInsert.Remove(sqlInsert.Lenght-1)+";"; //Remove a ultima virgula

    SqlCommand cmd = new SqlCommand(sqlInsert, con);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();

As I mentioned before, I have not refactored the code by changing some existing problems. I recommend reading about using the parameters when using a SqlCommand: link

link

In addition, you have to deal with any errors that may occur.

    
26.02.2018 / 16:48