Ajuda ao inserir Com PreparedStatement no Mysql[Resolvido]

11 respostas
javamysql
D

Estou com o seguinte erro

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

Estou tetando inserir dados de um pojo usando um JFrame para armanezar no Banco mas não estou conseguindo qualquer ajuda eu agradeço

Classe Funcionario

/*
 * 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 Classes;

import java.io.Serializable;


/**
 *
 * @author Douglas
 */

public class Funcionario implements Serializable {

    
    
    private Integer ID_Funcionario;
    private String datadeAdmissao;
    private String datadeDemissao;
    private String nome;
    private String estadoCivil;
    private String sexo;
    private String cep;
    private String cpf;
    private String rg;
    private String datadeNascimento;
    private String estado;
    private String cidade;
    private String bairro;
    private String endereco;
    private String tel;
    private String cel;
    private String email;
    private String cargo;
    private String niveldeEscolaridade;

   
    
     public Funcionario() {
     
    }
    

    public Funcionario(Integer ID_Funcionario) {
     this.ID_Funcionario=ID_Funcionario;
    }

    

    public Integer getID_Funcionario() {
        return ID_Funcionario;
    }
    
    
    public void setID_Funcionario(Integer ID_Funcionario) {
        this.ID_Funcionario = ID_Funcionario;
    }

    public String getDatadeAdmissao() {
        return datadeAdmissao;
    }

    public void setDatadeAdmissao(String datadeAdmissao) {
        this.datadeAdmissao = datadeAdmissao;
    }

    public String getDatadeDemissao() {
        return datadeDemissao;
    }

    public void setDatadeDemissao(String datadeDemissao) {
        this.datadeDemissao = datadeDemissao;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEstadoCivil() {
        return estadoCivil;
    }

    public void setEstadoCivil(String estadoCivil) {
        this.estadoCivil = estadoCivil;
    }

    public String getSexo() {
        return sexo;
    }

    public void setSexo(String sexo) {
        this.sexo = sexo;
    }

    public String getCep() {
        return cep;
    }

    public void setCep(String cep) {
        this.cep = cep;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getRg() {
        return rg;
    }

    public void setRg(String rg) {
        this.rg = rg;
    }

    public String getDatadeNascimento() {
        return datadeNascimento;
    }

    public void setDatadeNascimento(String datadeNascimento) {
        this.datadeNascimento = datadeNascimento;
    }

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public String getCidade() {
        return cidade;
    }

    public void setCidade(String cidade) {
        this.cidade = cidade;
    }

    public String getBairro() {
        return bairro;
    }

    public void setBairro(String bairro) {
        this.bairro = bairro;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getCel() {
        return cel;
    }

    public void setCel(String cel) {
        this.cel = cel;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCargo() {
        return cargo;
    }

    public void setCargo(String cargo) {
        this.cargo = cargo;
    }

    public String getNiveldeEscolaridade() {
        return niveldeEscolaridade;
    }

    public void setNiveldeEscolaridade(String niveldeEscolaridade) {
        this.niveldeEscolaridade = niveldeEscolaridade;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (ID_Funcionario != null ? ID_Funcionario.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Funcionario)) {
            return false;
        }
        Funcionario other = (Funcionario) object;
        if ((this.ID_Funcionario == null && other.ID_Funcionario != null) || (this.ID_Funcionario != null && !this.ID_Funcionario.equals(other.ID_Funcionario))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Classes.Funcionario[ iDFuncionario=" + ID_Funcionario + " ]";
    }
    
}

Conexão Banco

package Conexao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;

public class Conexao_Banco 
{
    private static Connection connection;
    
    public static Connection getConnection()
    {
        if ( connection == null )
        {
            try
            {
                String url = "jdbc:mysql://localhost:3306/prestadora"; //Nome da base de dados
		String user = "root"; //nome do usuário do MySQL
		String password = "root"; //senha do MySQL
		
		Connection conexao = null;
		conexao = DriverManager.getConnection(url, user, password);
            }
            
            catch( SQLException e )
            {
                JOptionPane.showMessageDialog(null," Conectado " + e );                                                
            }
        }
        
        return connection;
    }
    
   
}

Tela de Inserir

private void btnCadActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
               
        
    
        
   String  sexo = null;
     if( Rad_Masc.isSelected() )
        {
           sexo = "Masculino";
        }
                
        
        if( Rad_Fem.isSelected() )
        {
         sexo = "Feminino";
        }
    
    
      try{
         Connection connection = Conexao_Banco.getConnection();
                
         String query = " insert into funcionario (DatadeAdmissao,Nome,EstadoCivil,Sexo,CEP,CPF,RG,DatadeNascimento,Estado,Cidade,Bairro,Endereco,TEL,CEL,Email,Cargo,NiveldeEscolaridade) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
         PreparedStatement statement = (PreparedStatement) connection.prepareStatement(query);
                 
      
     statement.setString(1,Txt_DatadeAd.getText());
     statement.setString(2,Txt_Nome.getText());
     statement.setString(3,Comb_EstCivil.getSelectedItem().toString());
     statement.setString(4,sexo);
     statement.setString(5,Txt_CEP.getText());
     statement.setString(6,Txt_CPF.getText());
     statement.setString(7,Txt_RG.getText());
     statement.setString(8,Txt_DatadeNasc.getText());
     statement.setString(9,Comb_EST.getSelectedItem().toString());
     statement.setString(10,Txt_Cid.getText());
     statement.setString(11,Txt_Bairro.getText());
     statement.setString(12,Txt_END.getText());
     statement.setString(13,Txt_TEL.getText());
     statement.setString(14,Txt_CEL.getText());
     statement.setString(15,Txt_Email.getText());
     statement.setString(16,Txt_Cargo.getText());
     statement.setString(17,Comb_NivelEsc.getSelectedItem().toString());
     statement.executeUpdate();           
     statement.close();
      }catch(SQLException e){
      e.printStackTrace(System.err);     
    //   JOptionPane.showMessageDialog(null,e.getCause().getMessage(),"Erro",0);   
             
        }
      
     
    
     
      
               
    }

11 Respostas

drsmachado

Só essa mensagem não permite saber a causa do problema.
Pode postar todo o stack trace da exceção?

D

isso aqui ?

run:

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

at Telas.Tela_IncluirFuncionario.btnCadActionPerformed(Tela_IncluirFuncionario.java:377)

at Telas.Tela_IncluirFuncionario.access$000(Tela_IncluirFuncionario.java:21)

at Telas.Tela_IncluirFuncionario$1.actionPerformed(Tela_IncluirFuncionario.java:113)

at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)

at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)

at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)

at java.awt.Component.processMouseEvent(Component.java:6533)

at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)

at java.awt.Component.processEvent(Component.java:6298)

at java.awt.Container.processEvent(Container.java:2236)

at java.awt.Component.dispatchEventImpl(Component.java:4889)

at java.awt.Container.dispatchEventImpl(Container.java:2294)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)

at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)

at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)

at java.awt.Container.dispatchEventImpl(Container.java:2280)

at java.awt.Window.dispatchEventImpl(Window.java:2746)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)

at java.awt.EventQueue.access$500(EventQueue.java:97)

at java.awt.EventQueue$3.run(EventQueue.java:709)

at java.awt.EventQueue$3.run(EventQueue.java:703)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)

at java.awt.EventQueue$4.run(EventQueue.java:731)

at java.awt.EventQueue$4.run(EventQueue.java:729)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

CONSTRUÍDO COM SUCESSO (tempo total: 10 segundos)
drsmachado

Exato.
Podemos começar por estas linhas:
at Telas.Tela_IncluirFuncionario.btnCadActionPerformed(Tela_IncluirFuncionario.java:377) at Telas.Tela_IncluirFuncionario.access$000(Tela_IncluirFuncionario.java:21) at Telas.Tela_IncluirFuncionario$1.actionPerformed(Tela_IncluirFuncionario.java:113)
O que tem em cada uma delas?

D

PreparedStatement statement = (PreparedStatement) connection.prepareStatement(query); 377

public class Tela_IncluirFuncionario extends javax.swing.JInternalFrame { 21

btnCadActionPerformed(evt); 113

drsmachado

Antes de chamar o prepareStatement aqui PreparedStatement statement = (PreparedStatement) connection.prepareStatement(query);, você faz o que?
Pelas características do erro, creio que o objeto connection não está instanciado, logo, ao invocar qualquer coisa dele (atributo ou método), lançará a NullPointerException.

D

Connection connection = Conexao_Banco.getConnection();

String query = " insert into funcionario (DatadeAdmissao,Nome,EstadoCivil,Sexo,CEP,CPF,RG,DatadeNascimento,Estado,Cidade,Bairro,Endereco,TEL,CEL,Email,Cargo,NiveldeEscolaridade) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
     PreparedStatement statement = (PreparedStatement) connection.prepareStatement(query);

Ta instanciado sim eu acho

D

drsmachado

Bom, pela linha Connection connection = Conexao_Banco.getConnection();, teoricamente sim. Mas, o que tem No método getConnection da classe Conexao_Banco (detalhe: a especificação javabeans instrui a utilizar nomes de classes sem o underscore (_). Ao invés disso, prefira unir as palavras e fazer uso do CamelCase).

D

isso aqui dentro dela

package Conexao;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import javax.swing.JOptionPane;
public class Conexao_Banco

{

private static Connection connection;
public static Connection getConnection()
{
    if ( connection == null )
    {
        try
        {
            String url = "jdbc:mysql://localhost:3306/prestadora"; //Nome da base de dados
	String user = "root"; //nome do usuário do MySQL
	String password = "root"; //senha do MySQL
	
	Connection conexao = null;
	conexao = DriverManager.getConnection(url, user, password);
        }
        
        catch( SQLException e )
        {
            JOptionPane.showMessageDialog(null," Conectado " + e );                                                
        }
    }
    
    return connection;
}

}

drsmachado

Acabamos de encontrar o problema. Efetivamente o objeto de Connection está nulo, veja:
public static Connection getConnection() { if ( connection == null ){ se está nulo, executa o seguinte trecho:
Connection conexao = null; aqui você cria um novo objeto de Connection chamado conexão, que não é o connection
conexao = DriverManager.getConnection(url, user, password);
Aqui você atribuiu a conexão ao objeto que foi criado acima.

return connection;`

Aqui você retorna o connection que é nulo.
Sugiro fazer isso:
connection = DriverManager.getConnection(url, user, password);

D

Era isso mesmo nem percerbir esse deslize na conexão,obrigado por me ajudar

Criado 7 de março de 2017
Ultima resposta 7 de mar. de 2017
Respostas 11
Participantes 2