Save changes to the bank

Asked

Viewed 82 times

3

I am trying to change the data saved in the Database, basically when I double click on DataGrid he populates my TextBoxs to make the changes in the bank, but when I click to save it from the following error. Detail this error only happens when I add one more value to the txtPreco, if I delete what was inserted and put another value it registers a new product (which is not supposed to happen when I edit)

here the photo from the database

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

this is my code I’m using to try to change the data registered in the database

  //criando a bool
        bool informacoesSalvas = false;

        private void btnSalvar_Click(object sender, EventArgs e)
        {

        if (string.IsNullOrWhiteSpace(txtNome.Text))
        {
            System.Windows.Forms.MessageBox.Show("O nome do produto está vazio, por favor digite algo");
            return; // sai do método
        }
        else if (string.IsNullOrWhiteSpace(txtPreco.Text))
        {
            System.Windows.Forms.MessageBox.Show("O Preço do produto está vazio, por favor digite algo");
            return;
        }

        else if (informacoesSalvas)
        {

            // Abre a conexão
            conectar.Open();

            //Query SQL
            MySqlCommand command = new MySqlCommand("INSERT INTO Produto (Nome,Descricao,Preco)" +
            "VALUES('" + txtNome + "','" + txtDescricao.Text + "','" + txtPreco.Text + "' )", conectar);

            //Executa a Query SQL
            command.ExecuteNonQuery();

            // Fecha a conexão
            conectar.Close();

            //Mensagem de Sucesso
            MessageBox.Show("Alterado com Sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);

            informacoesSalvas = true;
        }
        else
        {
            conectar.Open();
            //Convertendo

            Converter = Convert.ToDecimal(txtPreco.Text);

            //MessageBox.Show("Conectado");

            MySqlCommand Inserir = new MySqlCommand();
            Inserir.Connection = conectar;
            Inserir.CommandText = "INSERT INTO Produto (Nome, Descricao, Preco, `status`) VALUES (@peca, @nome, @quantidade, @dataentrada)";

            Inserir.Parameters.AddWithValue("@peca", txtNome.Text);
            Inserir.Parameters.AddWithValue("@nome", txtDescricao.Text);
            Inserir.Parameters.AddWithValue("@quantidade", txtPreco.Text);
            Inserir.Parameters.AddWithValue("@dataentrada", ckbAtiv.Checked);

            Inserir.ExecuteNonQuery();
            conectar.Close();
            MessageBox.Show("Produto Cadastrado", "Concluido",
              MessageBoxButtons.OK,
              MessageBoxIcon.Information);
            selecionarCategoria();
        }
    }
  • 2

    I think it’s not your code that’s the problem, it’s your bank insertion. There is something wrong with your 'Price' column, it may be that this column does not exist in your current table or you are trying to insert some type of variable that is not accepted by the type of your column, for example, add a string in a double column. You checked out this information I mentioned?

  • What value goes in the text txtPreco.Text? In the database the column Preco is of what type?

  • The database of the column Preco it’s double, I’ll put a photo from the database

  • 1

    What is the value of the property Inserir.CommandText?And show the line you pass the parameter on @Preco.

  • @Augustovasques did not understand very well, I’m starting in C# yet. could explain a little better

  • 1

    Ali in the picture is giving error in Inserir.ExecuteNonQuery() i want to know the value of the property CommandText of the object Inserir.

  • 1

    I guess that’s it? Inserir.CommandText = "INSERT INTO Produto (Nome, Descricao, Preco, status) VALUES (@peca, @nome, @quantidade, @dataentrada)";

  • 1

    I would also like to see the line on Inserir.Parameters.AddWithValues(... where the first parameter is @Preco

  • 1

    That’s the mistake right there :Inserir.CommandText = "INSERT INTO Produto (Nome, Descricao, Preco, status) VALUES (@peca, @nome, @quantidade, @dataentrada)"; the parameters do not match

  • 1

    Opa I’ll try here to see how it unfolds

  • Needs to be put in the same order ?

  • 1

    yes and has to be compatible.

  • OK, I’m modifying and I’ll compile to see how it unfolds, thank you @Augustovasques

  • @Augustovasques good he started to only register the product, still can not save the changes

  • 1

    You have to open one data transaction insert into database using command commit and that’s the only way he can record in the database.

  • 1

    I’m kind of young, can you give me an example of how to do this ?

  • @Augustovasques, the example you presented was good, and I’m using, however it still only register, I decided to do it on another button but gave another error, follow the link of the other error link

Show 12 more comments

2 answers

2

Using a fragment of your example to show the use of Begintransaction and Commit.

note: I copied exactly the same content of the question.

    conectar.Open();

    //inicia a transação de dados
    var transaction = conectar.BeginTransaction();


    MySqlCommand command = new MySqlCommand("INSERT INTO Produto (Nome,Descricao,Preco)" +
    "VALUES('" + txtNome + "','" + txtDescricao.Text + "','" + txtPreco.Text + "' )", conectar);

    //insere os dados.
    command.ExecuteNonQuery();

    // Fecha a transação de dados salvando as alterações efetuadas
    transaction.Commit();


    conectar.Close();

0


Good people that was how I managed to solve this problem, now already this changing in the bank

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        lblID.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
        txtNome.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
        txtDescricao.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
        txtPreco.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
        alterar = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());


        Converter = Convert.ToDecimal(txtPreco.Text);

    }

    private void btnSalvar2_Click(object sender, EventArgs e)
    {
        MySqlConnection conectar = new MySqlConnection("server=127.0.0.1;database=ProdPacote; Uid=root; pwd=1234;");
        conectar.Open();
        var transaction = conectar.BeginTransaction();
        if (alterar <= 0)
        {
            MySqlCommand Inserir = new MySqlCommand();
            Inserir.Connection = conectar;
            Inserir.CommandText = "INSERT INTO Produto (Nome, Descricao, Preco, `status`) VALUES (@Nome, @Descricao, @Preco, @status)";

            Inserir.Parameters.AddWithValue("@Nome", txtNome.Text);
            Inserir.Parameters.AddWithValue("@Descricao", txtDescricao.Text);
            Inserir.Parameters.AddWithValue("@Preco", txtPreco.Text);
            Inserir.Parameters.AddWithValue("@status", ativIndat);
            Inserir.ExecuteNonQuery();

            transaction.Commit();
            conectar.Close();
            MessageBox.Show("Produto cadastrado", "Concluido",
            MessageBoxButtons.OK,
            MessageBoxIcon.Information);
            selecionarCategoria();

        }
        else
        {
            conectar.Close();
            conectar.Open();
            //Convertendo

            Converter = Convert.ToDecimal(txtPreco.Text);

            //MessageBox.Show("Conectado");

            MySqlCommand Inserir = new MySqlCommand();
            Inserir.Connection = conectar;
            Inserir.CommandText = "UPDATE  Produto SET Nome = '"+txtNome.Text+"', Descricao = '"+txtDescricao.Text+"', Preco ="+Converter+", status = "+ativIndat +" WHERE ID_Produto ="+alterar+" ";


            Inserir.ExecuteNonQuery();
            conectar.Close();
            alterar = 0;
            txtNome.Text = "";
            txtPreco.Text = "";
            txtDescricao.Text = "";
            MessageBox.Show("Produto alterado", "Concluido",
              MessageBoxButtons.OK,
              MessageBoxIcon.Information);
            selecionarCategoria();


        }

Browser other questions tagged

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