What’s the UPDATE error? (Java with Database)

Asked

Viewed 106 times

0

Hello, I am developing for the first time a system in Java with Database and there is some error in the Update that since yesterday I look for and not found. The error is that when I click to update, it does not update, it sends a message that has been updated but in the database and in the table remains the same thing. I’ll put the codes down here.

    package model.dao;

import conexao.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import model.bean.Financas;

public class FinancasDAO { //Essa classe é que faz a conexão com o banco de dados
    public void create(Financas Fin){
        Connection conexao = ConnectionFactory.getConnection();
        PreparedStatement prepState = null;
        try {
            prepState = conexao.prepareStatement("INSERT INTO financas (descricao,valor,quantidade,data)VALUES(?,?,?,?)");
            prepState.setString(1, Fin.getDescricao());
            prepState.setString(2, Double.toString(Fin.getValor()));
            prepState.setString(3, Integer.toString(Fin.getQuantidade()));
            prepState.setString(4, Fin.getData());


            prepState.executeUpdate();
            JOptionPane.showMessageDialog(null, "Salvo com Sucesso!");
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao Salvar: "+ex);
        }finally{
            ConnectionFactory.CloseConnection(conexao, prepState);
        }
}
    public List<Financas> listar(){
        Connection conexao = ConnectionFactory.getConnection();
        PreparedStatement prepState = null;
        ResultSet rs = null;

        List<Financas> financa = new ArrayList<>();

        try {
            prepState = conexao.prepareStatement("SELECT id, descricao, valor, quantidade, data FROM financas");
           rs = prepState.executeQuery();
           while(rs.next()){
               Financas Fin = new Financas();
               Fin.setId(rs.getInt("id"));
               Fin.setDescricao(rs.getString("descricao"));
               Fin.setValor(rs.getDouble("valor"));
               Fin.setQuantidade(rs.getInt("quantidade"));
               Fin.setData(rs.getString("data"));


               financa.add(Fin);
           }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro: "+ex);
        }
        finally{
            ConnectionFactory.CloseConnection(conexao, prepState, rs);
        }
        return financa;
    }


    public void update(Financas Fin){
        Connection conexao = ConnectionFactory.getConnection();
        PreparedStatement prepState = null;
        try {
            prepState = conexao.prepareStatement("UPDATE financas SET descricao = ?,valor = ?,quantidade = ?,data = ? WHERE id = ?");
            prepState.setString(1, Fin.getDescricao());
            prepState.setDouble(2, Fin.getValor());
            prepState.setInt(3, Fin.getQuantidade());
            prepState.setString(4, Fin.getData());
            prepState.setInt(5, Fin.getId());



            prepState.executeUpdate();
            JOptionPane.showMessageDialog(null, "Atualizado com Sucesso!");
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao Atualizar: "+ex);
        }finally{
            ConnectionFactory.CloseConnection(conexao, prepState);
        }
}

}

This class below is from Jframe that shows in the table the data.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import model.bean.Financas;
import model.dao.FinancasDAO;
//import javax.swing.text.TableView;

/**
 *
 * @author franc
 */
public class TelaCadastroConta extends javax.swing.JFrame {

    /**
     * Creates new form TelaCadastroConta
     */
    public TelaCadastroConta() {
        initComponents();
        DefaultTableModel modelo = (DefaultTableModel) tabela_txt.getModel();
        tabela_txt.setRowSorter(new TableRowSorter(modelo));
        readJTable();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    public void readJTable() {
        DefaultTableModel modelo = (DefaultTableModel) tabela_txt.getModel();
        FinancasDAO FinDAO = new FinancasDAO();
        modelo.setNumRows(0); //para nao duplicar valores da tabela

        for (Financas Fin : FinDAO.listar()) {
            modelo.addRow(new Object[]{
                Fin.getId(),
                Fin.getDescricao(),
                Fin.getValor(),
                Fin.getQuantidade(),
                Fin.getData()
            });
        }
    }

    public String dataParaMySQL(String data) { //metodo para converter DATA
        String dia = data_txt.getText().substring(0, 2);
        String mes = data_txt.getText().substring(3, 5);
        String ano = data_txt.getText().substring(6);
        String dataParaMySQL = ano + "-" + mes + "-" + dia;
        return dataParaMySQL;
        //13/05/2019    ano, mes, dia  2019-05-13  
    }

    public String dataVoltaMySQL(String data) { //metodo para converter DATA
        String dia = tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 4).toString().substring(8, 10);
        String mes = tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 4).toString().substring(5, 7);
        String ano = tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 4).toString().substring(0, 4);
        String dataParaMySQL = dia + "/" + mes + "/" + ano;
        //tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 3).toString();
        return dataParaMySQL;
    }

    public void dataAtualizaMySQL() { //metodo para converter DATA
        String dia = data_txt.getText().substring(8, 10);
        String mes = data_txt.getText().substring(5, 7);
        String ano = data_txt.getText().substring(0, 4);
        String dataParaMySQL = dia + "/" + mes + "/" + ano;
        data_txt.setText(dataParaMySQL);

    }



    private void botao_cadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                                
        Financas Fin = new Financas();
        FinancasDAO FinDAO = new FinancasDAO();

        if (descricao_txt.getText().equals("") || valor_txt.getText().equals("") || qtd_txt.getText().equals("") || data_txt.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Nenhum campo pode ficar em branco");
        } else {
            Fin.setDescricao(descricao_txt.getText());
            Fin.setValor(Double.parseDouble(valor_txt.getText()));
            Fin.setQuantidade(Integer.parseInt(qtd_txt.getText()));
            Fin.setData(dataParaMySQL(data_txt.getText()));
            FinDAO.create(Fin);
        }

        descricao_txt.setText("");
        valor_txt.setText("");
        qtd_txt.setText("");
        data_txt.setText("");

        readJTable();


    }                                               

//Na hora que seleciono na tabela e coloco os valores para alterar e clico no botao atualizar deveria atualizar na tabela
    private void botao_atualizarActionPerformed(java.awt.event.ActionEvent evt) {                                                
        if (tabela_txt.getSelectedRow() != -1) {

            Financas Fin = new Financas();
            FinancasDAO FinDAO = new FinancasDAO();

            if (descricao_txt.getText().equals("") || valor_txt.getText().equals("") || qtd_txt.getText().equals("") || data_txt.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "Nenhum campo pode ficar em branco");
            } else {
                Fin.setDescricao(descricao_txt.getText());
                Fin.setValor(Double.parseDouble(valor_txt.getText()));
                Fin.setQuantidade(Integer.parseInt(qtd_txt.getText()));
                Fin.setData(dataParaMySQL(data_txt.getText()));
                FinDAO.update(Fin);
            }

            descricao_txt.setText("");
            valor_txt.setText("");
            qtd_txt.setText("");
            data_txt.setText("");

            readJTable();
        }
    }                                               

    private void tabela_txtMouseClicked(java.awt.event.MouseEvent evt) {                                        
        if (tabela_txt.getSelectedRow() != -1) {
            descricao_txt.setText(tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 1).toString());
            valor_txt.setText(tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 2).toString());
            qtd_txt.setText(tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 3).toString());
            String data = tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 4).toString();
            data_txt.setText(dataVoltaMySQL(data));
        } else {
            JOptionPane.showMessageDialog(null, "Nenhuma linha selecionada");
        }
    }                                       

    private void tabela_txtKeyReleased(java.awt.event.KeyEvent evt) {                                       
        if (tabela_txt.getSelectedRow() != -1) {
            descricao_txt.setText(tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 1).toString());
            valor_txt.setText(tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 2).toString());
            qtd_txt.setText(tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 3).toString());
            String data = tabela_txt.getValueAt(tabela_txt.getSelectedRow(), 4).toString();
            data_txt.setText(dataVoltaMySQL(data));
        } else {
            JOptionPane.showMessageDialog(null, "Nenhuma linha selecionada");
        }
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaCadastroConta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaCadastroConta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaCadastroConta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaCadastroConta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaCadastroConta().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JToggleButton botao_atualizar;
    private javax.swing.JButton botao_cadastrar;
    private javax.swing.JButton botao_excluir;
    private javax.swing.JFormattedTextField data_txt;
    private javax.swing.JTextField descricao_txt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField qtd_txt;
    private javax.swing.JTable tabela_txt;
    private javax.swing.JTextField valor_txt;
    // End of variables declaration                   
}
  • The ideal in this case would be for you to debug and verify what are the values of the parameters you are passing to the method. The query for the database is written correctly, just know if it found any value with this id. Where you enter the id?

  • Thanks, it was Id’s drug that was different, always went as 0.

  • For nothing, give a vote ai in comment, to strengthen friendship, please kkkk

No answers

Browser other questions tagged

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