Delete button function does not work

Asked

Viewed 120 times

0

I’m developing a software for tcc I have already created the connection to the database and the function of entering data into the database when programming the following code to delete button, it returns nothing and the button does not work:

try {
    PreparedStatement pst = conecta.con.prepareStatement("delete from classe where id="+id+"");
} catch (SQLException ex) {
    Logger.getLogger(CriarClasse.class.getName()).log(Level.SEVERE, null, ex);
}

related to JAVA.:

/*
 * 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 java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class ConexaoDB {
public Statement stmt;
public ResultSet rs;
private String driver = "com.mysql.jdbc.Driver";
private String host = "jdbc:mysql://localhost:3306/escola";
private String usuario = "root";
private String senha = "";
public Connection con;

public void conexao(){
    try {
        System.setProperty("jdbc.Drivers", driver);
        con= DriverManager.getConnection(host, usuario, senha);
        //JOptionPane.showMessageDialog(null, "Conectado com sucesso!");
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Erro de conexão!\n Erro: "+ex.getMessage());
    }
}

public void executaSQL(String sql){
    try { 
        stmt = con.createStatement(rs.TYPE_SCROLL_INSENSITIVE, rs.CONCUR_READ_ONLY);
        rs = stmt.executeQuery(sql);
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Erro no executaSQL!\n Erro: "+ex.getMessage());
    }
}

public void desconectar(){
    try {
        con.close();
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Erro ao fechar a conexão!\n Erro: "+ex.getMessage());
    }    
}



}

Create JAVA Class.

/*
 * 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 java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author marco
 */
public class CriarClasse extends javax.swing.JFrame {

    ConexaoDB conecta = new ConexaoDB();
    /**
     * Creates new form CriarClasse
     */
    public CriarClasse() {
        initComponents();
        conecta.conexao();
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lbltitulo = new javax.swing.JLabel();
        lblclasse = new javax.swing.JLabel();
        campoclasse = new javax.swing.JTextField();
        lblsetor = new javax.swing.JLabel();
        camposetor = new javax.swing.JTextField();
        btncriar = new javax.swing.JButton();
        btnatualizar = new javax.swing.JButton();
        btndeletar = new javax.swing.JButton();
        btnfechar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabela1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(0, 153, 153));

        lbltitulo.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
        lbltitulo.setForeground(new java.awt.Color(255, 255, 255));
        lbltitulo.setText("Criar Classe");

        lblclasse.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblclasse.setForeground(new java.awt.Color(255, 255, 255));
        lblclasse.setText("Nome da classe:");

        lblsetor.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblsetor.setForeground(new java.awt.Color(255, 255, 255));
        lblsetor.setText("Setor:");

        btncriar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btncriar.setText("Criar");
        btncriar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btncriarActionPerformed(evt);
            }
        });

        btnatualizar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnatualizar.setText("Atualizar");
        btnatualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnatualizarActionPerformed(evt);
            }
        });

        btndeletar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btndeletar.setText("Deletar");
        btndeletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btndeletarActionPerformed(evt);
            }
        });

        btnfechar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnfechar.setText("Fechar");
        btnfechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnfecharActionPerformed(evt);
            }
        });

        tabela1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "CLASSE", "SETOR"
            }
        ));
        tabela1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabela1MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tabela1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(98, 98, 98)
                        .addComponent(lbltitulo))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblsetor)
                            .addComponent(lblclasse))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(campoclasse)
                                .addComponent(camposetor, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(btndeletar, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                                    .addComponent(btncriar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(btnatualizar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(btnfechar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(lbltitulo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblclasse)
                    .addComponent(campoclasse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblsetor)
                    .addComponent(camposetor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnatualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btncriar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btndeletar)
                    .addComponent(btnfechar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void tabela1MouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        int indexrow= tabela1.getSelectedRow();

        DefaultTableModel model = (DefaultTableModel)tabela1.getModel();
        id=model.getValueAt(indexrow, 0).toString();
        campoclasse.setText(model.getValueAt(indexrow, 1).toString());
        camposetor.setText(model.getValueAt(indexrow, 2).toString());        
    }                                    

    private void btncriarActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // TODO add your handling code here:
            PreparedStatement pst= conecta.con.prepareStatement("insert into classe (classe,setor) values(?,?) ");
            pst.setString(1, campoclasse.getText());
            pst.setString(2, camposetor.getText());
            pst.executeUpdate();
            JOptionPane.showMessageDialog(rootPane, "Criado com sucesso!");
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(rootPane, "Erro na inserção!\n Erro: "+ex);
        }
    }                                        
String id;
    private void btnatualizarActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
    }                                            

    private void btndeletarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        try {
            PreparedStatement pst = conecta.con.prepareStatement("delete from classe where id="+id+"");
        } catch (SQLException ex) {
            Logger.getLogger(CriarClasse.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                          

    private void btnfecharActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
    }                                         

    /**
     * @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 ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CriarClasse.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CriarClasse.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CriarClasse.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CriarClasse.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnatualizar;
    private javax.swing.JButton btncriar;
    private javax.swing.JButton btndeletar;
    private javax.swing.JButton btnfechar;
    private javax.swing.JTextField campoclasse;
    private javax.swing.JTextField camposetor;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblclasse;
    private javax.swing.JLabel lblsetor;
    private javax.swing.JLabel lbltitulo;
    private javax.swing.JTable tabela1;
    // End of variables declaration                   
}

CONEXAODB: inserir a descrição da imagem aqui

CREATE JAVA CLASS. inserir a descrição da imagem aqui

Fiz desta maneira, está funcionando mas não sei se pode acarretar algum problema de memoria:

        if(id!=null)
        {

            try{
                PreparedStatement pst= conecta.con.prepareStatement("delete from classe where id="+id+" ");
                Statement stmt= conecta.con.createStatement();
                pst.execute();
                JOptionPane.showMessageDialog(null, "Deletado!");
                getdata();
                vazio();

            }
            catch(Exception e)
            {
                JOptionPane.showMessageDialog(null, "Error!"+e);
            }
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Selecione um item para deletar!");
        }        
  • you have seen what the "id" value is when mounting the delete command?

1 answer

1


Hi,

I think you need to commit.

suaConexao.commit();

Browser other questions tagged

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