Mensagem de Erro - Firebird

9 respostas
Ment0r
Olá amigos, venho mais uma vez usufluir de vosso conhecimento rsrs.

Bom, eu tenho um programinha bem simples, ele cadastra clientes. Uso o firebird 2.1.1 para guardar os dados, mas o que ta acontecendo é o seguinte:

Aparece essa mensagem de erro>

Exception in thread AWT-EventQueue-0 java.lang.NullPointerException

at CadastroCliente.btCadastrar_Click(CadastroCliente.java:162)

at CadastroCliente$1.actionPerformed(CadastroCliente.java:103)

at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)

at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)

at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)

at javax.swing.DefaultButtonModel.setPressed(Unknown Source)

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)

at java.awt.Component.processMouseEvent(Unknown Source)

at javax.swing.JComponent.processMouseEvent(Unknown Source)

at java.awt.Component.processEvent(Unknown Source)

at java.awt.Container.processEvent(Unknown Source)

at java.awt.Component.dispatchEventImpl(Unknown Source)

at java.awt.Container.dispatchEventImpl(Unknown Source)

at java.awt.Component.dispatchEvent(Unknown Source)

at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)

at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)

at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)

at java.awt.Container.dispatchEventImpl(Unknown Source)

at java.awt.Window.dispatchEventImpl(Unknown Source)

at java.awt.Component.dispatchEvent(Unknown Source)

at java.awt.EventQueue.dispatchEvent(Unknown Source)

at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)

at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)

at java.awt.EventDispatchThread.pumpEvents(Unknown Source)

at java.awt.EventDispatchThread.pumpEvents(Unknown Source)

at java.awt.EventDispatchThread.run(Unknown Source)

A conexão é estabelecida, mas quando eu clico no botão cadastrar, acontece o que eu descrevi acima.

Erro linha 103

btCadastrar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ btCadastrar_Click();//erro linha 103 } });

Erro linha 162

try{ Statement stm = con.createStatement();//linha 162 stm.execute(sql); System.out.println("[Dados Incluidos]"); }catch(SQLException sql){System.out.print("[Erro na inclusão dos dados]");}; btLimpar_Click(); }

Por que será hein amigos, se alguém souber agradeço desde já.

9 Respostas

joede.fadel

como que vc faz a instancia da sua conexão?? pois esse erro parece se no “con”

Ment0r

try { Class.forName("org.firebirdsql.jdbc.FBDriver"); Connection con = DriverManager.getConnection( "jdbc:firebirdsql:localhost:C:/ProjetoChuchu/CHUCHUDB.FDB", "sysdba", "masterkey"); System.out.println("Conexão estabelecida com sucesso !!!"); } catch (Exception e) { System.out.println("Não foi possível conectar ao banco: " + e.getMessage()); } }

joede.fadel

olha pelo que eu olhei ta certo, amenos que vc esteja fazendo isso em classes separadas, se esse for o caso declare o objeto static Connection con.

Ment0r

Não joede.fadel está tudo na mesma classe, não sei tbm o porquê disso cara, to quebrando a cabeça faz tempo viu.
Obrigado.

joede.fadel

poste a classe inteira

Ment0r
import javax.swing.*;
import java.io.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

import javax.swing.JButton;

public class CadastroCliente extends JFrame{
	public Connection con;
    private JButton btCadastrar, btLimpar;
    private JPanel pnlOeste, pnlLeste, pnlSul;
    private String sql = null;
    private JLabel lbTitulo;
    private JLabel lbCodigo, lbNome, lbEndereco, lbBairro, lbCidade, lbCep, lbEstado, 
    lbDataNascimento, lbSexo, lbCpf, lbRg, lbTelefone, lbEmail;
    private JTextField tfCodigo, tfNome, tfEndereco, tfBairro, tfCidade, tfCep, tfEstado, 
    tfDataNascimento, tfSexo, tfCpf, tfRg, tfTelefone, tfEmail;
   
    public CadastroCliente() {
    	setTitle("CADASTRO DE CLIENTE");
    	
    	//declaração do container
    	Container cp = getContentPane();
    
    	Icon imgMenu = new ImageIcon("imagens/imgCadastroCliente.jpg");
    	
    	//instaciação dos botões
    	btCadastrar = new JButton("Cadastrar");
    	btLimpar = new JButton("Limpar Campos");
    	
    	//instciação dos textfields
    	tfCodigo = new JTextField(15);
    	tfNome = new JTextField(15);
    	tfEndereco = new JTextField(15);
    	tfBairro = new JTextField(15);
    	tfCidade = new JTextField(15);
    	tfCep = new JTextField(15);
    	tfEstado = new JTextField(15);
    	tfDataNascimento = new JTextField(15);
    	tfSexo = new JTextField(15);
    	tfCpf = new JTextField(15);
    	tfRg = new JTextField(15);
    	tfTelefone = new JTextField(15);
    	tfEmail = new JTextField(15);
    	
    	//instaciação dos labels
    	lbCodigo = new JLabel("Codigo:");
    	lbNome = new JLabel("Nome:");
    	lbEndereco = new JLabel("Endereço:");
    	lbBairro = new JLabel("Bairro:");
    	lbCidade = new JLabel("Cidade:");
    	lbCep = new JLabel("Cep:");
    	lbEstado = new JLabel("Estado:");
    	lbDataNascimento = new JLabel("Data de Nascimento:");
    	lbSexo = new JLabel("Sexo:");
    	lbCpf = new JLabel("CPF:");
    	lbRg = new JLabel("RG:");
       	lbTelefone = new JLabel("Telefone:");
       	lbEmail = new JLabel("e-mail:");
       	
    	lbTitulo = new JLabel("", imgMenu, JLabel.CENTER);
       
    	pnlOeste = new JPanel(new GridLayout(7,2));
    	pnlOeste.add(lbCodigo);pnlOeste.add(tfCodigo);
    	pnlOeste.add(lbNome);pnlOeste.add(tfNome);
    	pnlOeste.add(lbEndereco);pnlOeste.add(tfEndereco);
    	pnlOeste.add(lbBairro);pnlOeste.add(tfBairro);
    	pnlOeste.add(lbCidade);pnlOeste.add(tfCidade);
    	pnlOeste.add(lbCep);pnlOeste.add(tfCep);
    	pnlOeste.add(lbEstado);pnlOeste.add(tfEstado);

     	pnlLeste = new JPanel(new GridLayout(6,2,4,4));
     	pnlLeste.add(lbDataNascimento);pnlLeste.add(tfDataNascimento);
     	pnlLeste.add(lbSexo);pnlLeste.add(tfSexo);
     	pnlLeste.add(lbCpf);pnlLeste.add(tfCpf);
     	pnlLeste.add(lbRg);pnlLeste.add(tfRg);
     	pnlLeste.add(lbTelefone);pnlLeste.add(tfTelefone);
     	pnlLeste.add(lbEmail);pnlLeste.add(tfEmail);
     	
     	pnlSul = new JPanel(new GridLayout(1,2));
     	pnlSul.add(btCadastrar);
     	pnlSul.add(btLimpar);

    	//definição do layout
    	cp.setLayout(new BorderLayout());
    	
    	//adição dos itens no container
    	cp.add("North", lbTitulo);
    	cp.add("East", pnlLeste);
    	cp.add("West", pnlOeste);
    	cp.add("South", pnlSul);
    	
    	setLocation(150, 250);
    	pack();
    	
    	//action listenter
    	btCadastrar.addActionListener(new ActionListener() {
    		public void actionPerformed(ActionEvent e){
    			btCadastrar_Click();
    		}
    		});
    	
    	btLimpar.addActionListener(new ActionListener() {
    		public void actionPerformed(ActionEvent e){
    			btLimpar_Click();
    		}
    		});
    }
	
	public static void main(String[] args) {
		new CadastroCliente().setVisible(true);
		
		try {  
			Class.forName("org.firebirdsql.jdbc.FBDriver");
			Connection con = DriverManager.getConnection(  
					"jdbc:firebirdsql:localhost:C:/ProjetoChuchu/CHUCHUDB.FDB",  
					"sysdba",  
					"masterkey");
			System.out.println("Conexão estabelecida com sucesso !!!");
			} catch (Exception e) {  
				System.out.println("Não foi possível conectar ao banco " + e.getMessage());  
			}
		}

	public void btCadastrar_Click(){
		if (tfCodigo.getText().trim().length()!=0 && 
			tfNome.getText().trim().length()!=0 &&
			tfEndereco.getText().trim().length()!=0 &&
			tfBairro.getText().trim().length()!=0 &&
			tfCidade.getText().trim().length()!=0 &&
			tfCep.getText().trim().length()!=0 &&
			tfEstado.getText().trim().length()!=0 &&
			tfDataNascimento.getText().trim().length()!=0 &&
			tfSexo.getText().trim().length()!=0 &&
			tfCpf.getText().trim().length()!=0 &&
			tfRg.getText().trim().length()!=0 &&
			tfTelefone.getText().trim().length()!=0 &&
			tfEmail.getText().trim().length()!=0){
			
			String sCodigo = tfCodigo.getText();
			String sNome = tfNome.getText();
			String sEndereco = tfEndereco.getText();
			String sBairro = tfBairro.getText();
			String sCidade = tfCidade.getText();
			String sCep = tfCep.getText();
			String sEstado = tfEstado.getText();
			String sDataNascimento = tfDataNascimento.getText();
			String sSexo = tfSexo.getText();
			String sCpf = tfCpf.getText();
			String sRg = tfRg.getText();
			String sTelefone = tfTelefone.getText();
			String sEmail = tfEmail.getText();
			
			sql = "INSERT INTO CLIENTE(CODIGO, NOME, ENDERECO, BAIRRO, CIDADE, CEP, ESTADO, DATANASCIMENTO, CPF, RG, TELEFONE, EMAIL) " +
					"VALUES("+sCodigo+","+"'"+sNome+"'"+","+"'"+sEstado+"'"+","+"'"+sBairro+"'"+","+"'"+sCidade+"'"+","+sCep+","+"'"+sEndereco+"'"+","+sDataNascimento+","+"'"+sSexo+"'"+","+sCpf+","+sRg+","+sTelefone+","+"'"+sEmail+"'"+")";

			try{
				Statement stm = con.createStatement();
				stm.execute(sql);
				System.out.println("[Dados Incluidos]");
			}catch(SQLException sql){System.out.print("[Erro na inclusão dos dados]");};
			btLimpar_Click();
		}
			
			String sql = "INSERT INTO CLIENTE(CODIGO, NOME, ENDERECO, BAIRRO, CIDADE, CEP, ESTADO, DATANASCIMENTO, CPF, RG, TELEFONE, EMAIL) " +      
			"VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";  
	}
	
	public void btLimpar_Click(){
    	tfCodigo.setText("");
    	tfNome.setText("");
    	tfEndereco.setText("");
    	tfBairro.setText("");
    	tfCidade.setText("");
    	tfCep.setText("");
    	tfEstado.setText("");
    	tfDataNascimento.setText("");
    	tfSexo.setText("");
    	tfCpf.setText("");
    	tfRg.setText("");
    	tfTelefone.setText("");
    	tfEmail.setText("");
	}
}

Ele não apresenta erro e se conecta ao banco de dados, no entanto não consigo efetuar o cadastro. Assim que preencho os campos e clico no botão cadastrar ele exibe as mensagens descritas na primeira postagem.

Muito Obrigado desde já.

joede.fadel

Do jeito que vc ta fazendo não vai funcionar msmo
pois logo apos que o metodo main é executado o objeto con ele é destruido
faça assim

public Connection conectar(){ try { Class.forName("org.firebirdsql.jdbc.FBDriver"); Connection con = DriverManager.getConnection( "jdbc:firebirdsql:localhost:C:/ProjetoChuchu/CHUCHUDB.FDB", "sysdba", "masterkey"); System.out.println("Conexão estabelecida com sucesso !!!"); return con; } catch (Exception e) { System.out.println("Não foi possível conectar ao banco " + e.getMessage()); return null; } }

na hora que vc for utilizar a conexão

Statement stm = conectar().createStatement(); stm.executeUpdate(sql); System.out.println("[Dados Incluidos]");

Ment0r

Muito Obrigado joede.fadel, como vê sou bem iniciante na arte java. Perdoe minha ignorancia mas onde eu colo o primeiro trecho, no metodo MAIN? Eu colei abaixo do main.
Preenchi os campos e cliquei em cadastrar não aparece mais aquelas lista de erros, porém quando fui ao client do banco de dados e visualizei os dados, todos estavam null.

PS: o bd está ativo quando inseri os dados.

Grato, um abraço.

Ment0r

Amigos, após ajuda de vocês consegui resolver. O erro que persistia em continuar nada mais era de que a string que continha o comando sql. Essa estava com 3 campos invertidos rsrsrs. Agora está funcionando normalmente.

Muito obrigado a todos que ajudaram, Vlw msm.

Criado 20 de novembro de 2008
Ultima resposta 25 de nov. de 2008
Respostas 9
Participantes 2