Problema com o Insert no Banco - MSAcess

8 respostas
C

Pessoal sou inexperiente nesse assunto portanto vou direto ao ponto. Ao tentar inserir 2 valores digitados pelo usuario a partir da interface no banco de dados está acontecendo uma exceção do tipo JavaNullPointException. Segue o código:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        
        try {
            
            String sqlinsert = "INSERT INTO idPayoff (vetor,descricao_do_vetor) VALUES ('"+
                tf_Cadastro.getText()+"','"+
                tf_Descricao.getText()+"')";

            con_payoff.statement.executeUpdate(sqlinsert);
            
            JOptionPane.showMessageDialog(null, "Payoffs Inseridos com Sucesso");

            con_payoff.resultSet = con_payoff.statement.executeQuery("SELECT * FROM idPayoff");
            con_payoff.executeSQL("SELECT * FROM idPayoff");
            con_payoff.resultSet.first();

        } catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao inserir os seus Payoffs" + erro);
        } catch(Exception e){
            JOptionPane.showMessageDialog(null, "Erro desconhecido" + e);
        }

    }

O que está errado? Por favor se alguem puder me ajudar agradeço!

8 Respostas

lucas_carvalho100

CassianoHenrique:
Pessoal sou inexperiente nesse assunto portanto vou direto ao ponto. Ao tentar inserir 2 valores digitados pelo usuario a partir da interface no banco de dados está acontecendo uma exceção do tipo JavaNullPointException. Segue o código:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        
        try {
            
            String sqlinsert = "INSERT INTO idPayoff (vetor,descricao_do_vetor) VALUES ('"+
                tf_Cadastro.getText()+"','"+
                tf_Descricao.getText()+"')";

            con_payoff.statement.executeUpdate(sqlinsert);
            
            JOptionPane.showMessageDialog(null, "Payoffs Inseridos com Sucesso");

            con_payoff.resultSet = con_payoff.statement.executeQuery("SELECT * FROM idPayoff");
            con_payoff.executeSQL("SELECT * FROM idPayoff");
            con_payoff.resultSet.first();

        } catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao inserir os seus Payoffs" + erro);
        } catch(Exception e){
            JOptionPane.showMessageDialog(null, "Erro desconhecido" + e);
        }

    }

O que está errado? Por favor se alguem puder me ajudar agradeço!


Se não estou enganado não é possível dar um first no resultset… Mas em qual momento ele da o erro? Vc ja usou o debug?

yoshikichi

CassianoHenrique:
Pessoal sou inexperiente nesse assunto portanto vou direto ao ponto. Ao tentar inserir 2 valores digitados pelo usuario a partir da interface no banco de dados está acontecendo uma exceção do tipo JavaNullPointException. Segue o código:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        
        try {
            
            String sqlinsert = "INSERT INTO idPayoff (vetor,descricao_do_vetor) VALUES ('"+
                tf_Cadastro.getText()+"','"+
                tf_Descricao.getText()+"')";

            con_payoff.statement.executeUpdate(sqlinsert);
            
            JOptionPane.showMessageDialog(null, "Payoffs Inseridos com Sucesso");

            con_payoff.resultSet = con_payoff.statement.executeQuery("SELECT * FROM idPayoff");
            con_payoff.executeSQL("SELECT * FROM idPayoff");
            con_payoff.resultSet.first();

        } catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao inserir os seus Payoffs" + erro);
        } catch(Exception e){
            JOptionPane.showMessageDialog(null, "Erro desconhecido" + e);
        }

    }

O que está errado? Por favor se alguem puder me ajudar agradeço!

E ai blz?
pq vc faz dois select?

con_payoff.resultSet = con_payoff.statement.executeQuery("SELECT * FROM idPayoff"); con_payoff.executeSQL("SELECT * FROM idPayoff");
Nullpointer é tentar acessar objeto nulo, posta o código todo ai.
falow

C

Olá quando executo:

con_payoff.statement.executeUpdate(sqlinsert);

o programa levanta uma exceção desconhecida:

catch(Exception e){
            JOptionPane.showMessageDialog(null, "Erro desconhecido" + e);
        }

Mensagem:
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException

lucas_carvalho100

Esta vindo valores nos campos informado pelo usuário?

C

Fiz uma query SQL diretamente no Access e funciona. Mas no código não funciona! O usuário insere os dados e quando se executa a operação para gravar no banco o erro acontece na linha do sqlinsert. Sera algo no resultset?

lucas_carvalho100

Poste todo o código… Sem ver por exemplo a declaração dessa variável fica complicado…

con_payoff.statement.

C

Segue…

package spe.visao.gui;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import spe.persistencia.gateway.GerenciadorDeConexao;
import java.awt.Dimension;
import javax.swing.JOptionPane;



/**
 *
 * @author Henrique
 */
public class GUIPayoff extends javax.swing.JInternalFrame {

    GerenciadorDeConexao con_payoff;
    /** Creates new form GUIPayoff */
    public GUIPayoff() {
        initComponents();
        con_payoff = new GerenciadorDeConexao();
        
    }


    public void setPosicao(){
        Dimension d = this.getDesktopPane().getSize();
        this.setLocation((d.width - this.getSize().width) / 2,
                         (d.height - this.getSize().height)/2);
    }
    /** 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() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tf_Cadastro = new javax.swing.JTextField();
        tf_Descricao = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        bClose = new javax.swing.JButton();

        setTitle("PAYOFFS - BENS - CONSEQU?NCIAS");

        jRadioButton1.setText("Payoff Escalar");
        jRadioButton1.setToolTipText("O objeto P pode ser qualquer coisa, mas tem que ser bem definido. Selecione este caso se s? existe um par?metro a se consderar com diversas gradua??es.");

        jRadioButton2.setText("Payoff Vetorial");
        jRadioButton2.setToolTipText("O objeto Pj pode ser qualquer coisa, mas tem que ser bem definido. Selecione este caso se existirem v?rios par?metros a serem consderados, tendo cada um diversas gradua??es.");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Cadastro");

        jLabel2.setText("Descri??o");

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spe/visao/logo/100.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spe/visao/logo/17.png"))); // NOI18N

        bClose.setText("Fechar");
        bClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCloseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2))
                                .addGap(31, 31, 31)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(tf_Cadastro, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
                                    .addComponent(tf_Descricao, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jRadioButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 112, Short.MAX_VALUE)
                                .addComponent(jRadioButton2)))
                        .addGap(184, 184, 184))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(189, 189, 189)
                        .addComponent(bClose, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButton1)
                    .addComponent(jRadioButton2))
                .addGap(45, 45, 45)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(tf_Cadastro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(tf_Descricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(142, 142, 142)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(21, 21, 21)
                .addComponent(bClose)
                .addContainerGap())
        );

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

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        
        try {
            
            String sqlinsert = "INSERT INTO idPayoff (vetor,descricao_do_vetor) VALUES ('"+
                tf_Cadastro.getText()+"','"+
                tf_Descricao.getText()+"')";

            con_payoff.statement.executeUpdate(sqlinsert);
            
            JOptionPane.showMessageDialog(null, "Payoffs Inseridos com Sucesso");

            con_payoff.resultSet = con_payoff.statement.executeQuery("SELECT * FROM idPayoff");
            con_payoff.resultSet.next();

        } catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao inserir os seus Payoffs" + erro);
        } catch(Exception e){
            JOptionPane.showMessageDialog(null, "Erro desconhecido" + e);
        }
        con_payoff.desconecta();

    }                                        

    private void bCloseActionPerformed(java.awt.event.ActionEvent evt) {                                       
        this.dispose();
}                                      
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUIPayoff().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify                     
    private javax.swing.JButton bClose;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField tf_Cadastro;
    private javax.swing.JTextField tf_Descricao;
    // End of variables declaration                   

}
lucas_carvalho100

GerenciadorDeConexao con_payoff; A conexão esta sendo aberta normalmente?

Criado 23 de setembro de 2010
Ultima resposta 23 de set. de 2010
Respostas 8
Participantes 3