Ajuda com dados tipo Date

13 respostas
E

Boa noite,

Estou com problema no meu projeto no NetBeans com inserção de dados ao banco de dados, gostaria da ajuda de vocês.
Estou tentando usar o Evento jDateChooser só que , estou com problema ao usar o Date pois ele não aceita String, como faço para usar Getters e Setters com Date para enviar os dados para banco de dados, pois já tentei sempre da erro Exception in thread “AWT-EventQueue-0” java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date. Isso quando uso Date no lugar de String na Date(não sei se é o correto), pois só usei até agora dados do tipo String.

Espero que possam me ajudar.

Classe Aluno

package classesNegocios;

import classesDAO.AlunoDAO;
import java.sql.SQLException;
import util.QueryTableModel;


public class Aluno {
    private int matricula;
    private String nome;
    private String cpf;
    private String dtnascimento;
    private String telefone;
    private String endereco;
    private String cep;
    private String tipo;
    private String dtmatricula;
    private String email;

public void insert() throws SQLException{
 AlunoDAO dao = new AlunoDAO(this);
 dao.insert();
}
public void update() throws SQLException{
 AlunoDAO dao = new AlunoDAO(this);
 dao.update();
}
public void delete() throws SQLException{
 AlunoDAO dao = new AlunoDAO(this);
 dao.delete();
}
public static QueryTableModel getTableModel(){
   return AlunoDAO.getTableModel();
}


    /**
     * @return the matricula
     */
    public int getMatricula() {
        return matricula;
    }

    /**
     * @param matricula the matricula to set
     */
    public void setMatricula(int matricula) {
        this.matricula = matricula;
    }

    /**
     * @return the nome
     */
    public String getNome() {
        return nome;
    }

    /**
     * @param nome the nome to set
     */
    public void setNome(String nome) {
        this.nome = nome;
    }

    /**
     * @return the cpf
     */
    public String getCpf() {
        return cpf;
    }

    /**
     * @param cpf the cpf to set
     */
    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    /**
     * @return the data_nasc
     */
    public String getDtnascimento() {
        return dtnascimento;
    }

    /**
     * @param data_nasc the data_nasc to set
     */
    public void setDtnascimento(String dtnascimento) {
        this.dtnascimento = dtnascimento;
    }

    /**
     * @return the telefone
     */
    public String getTelefone() {
        return telefone;
    }

    /**
     * @param telefone the telefone to set
     */
    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    /**
     * @return the endereco
     */
    public String getEndereco() {
        return endereco;
    }

    /**
     * @param endereco the endereco to set
     */
    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    /**
     * @return the cep
     */
    public String getCep() {
        return cep;
    }

    /**
     * @param cep the cep to set
     */
    public void setCep(String cep) {
        this.cep = cep;
    }

    /**
     * @return the tipo
     */
    public String getTipo() {
        return tipo;
    }

    /**
     * @param tipo the tipo to set
     */
    public void setTipo(String tipo) {
        this.tipo = tipo;
    }

    /**
     * @return the data_mat
     */
    public String getDtmatricula() {
        return dtmatricula;
    }

    /**
     * @param data_mat the data_mat to set
     */
    public void setDtmatricula(String dtmatricula) {
        this.dtmatricula = dtmatricula;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

}

Classe AlunoDao

package classesDAO;

import util.DataBase;
import classesNegocios.Aluno;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import util.QueryTableModel;


public class AlunoDAO {

    private Aluno aluno = null;

    public AlunoDAO(Aluno a) {
        this.aluno = a;
    }

    public void insert() throws SQLException {
        String sql = "insert into "
                + "aluno (NOME,CPF,DTNASCIMENTO,TELEFONE,ENDERECO,CEP,EMAIL,DTMATRICULA,TIPO)"
                + "values(?,?,?,?,?,?,?,?,?)";
        DataBase conn = DataBase.getInstance();
        PreparedStatement query =
                conn.getConexao().prepareStatement(sql);
        query.setString(1, aluno.getNome());
        query.setString(2, aluno.getCpf());
        query.setString(3, aluno.getDtnascimento());
        query.setString(4, aluno.getTelefone());
        query.setString(5, aluno.getEndereco());
        query.setString(6, aluno.getCep());
        query.setString(7, aluno.getEmail());
        query.setString(8, aluno.getDtmatricula());
        query.setString(9, aluno.getTipo());
        query.executeUpdate();
        query.close();
    }

    public void update() throws SQLException {
        String sql = "UPDATE ALUNO "
                + "SET NOME = ?, "
                + "CPF = ? ,"
                + "DTNASCIMENTO = ?, "
                + "TELEFONE = ?, "
                + "ENDERECO = ?, "
                + "CEP = ?, "
                + "EMAIL = ? ,"
                + "DTMATRICULA = ?, "
                + "TIPO = ? "
                + "WHERE MATRICULA = ? ";
        DataBase conn = DataBase.getInstance();
        PreparedStatement query =
                conn.getConexao().prepareStatement(sql);
        query.setString(1, aluno.getNome());
        query.setString(2, aluno.getCpf());
        query.setString(3, aluno.getDtnascimento());
        query.setString(4, aluno.getTelefone());
        query.setString(5, aluno.getEndereco());
        query.setString(6, aluno.getCep());
        query.setString(7, aluno.getEmail());
        query.setString(8, aluno.getDtmatricula());
        query.setString(9, aluno.getTipo());
        query.setString(9, aluno.getTipo());
        query.setInt(10, aluno.getMatricula());
        query.executeUpdate();
        query.close();
    }

    public void delete() throws SQLException {
        String sql = "DELETE FROM ALUNO "
                + "WHERE MATRICULA = ?";
        DataBase conn = DataBase.getInstance();
        PreparedStatement query =
                conn.getConexao().prepareStatement(sql);
        query.setInt(1, aluno.getMatricula());
        query.executeUpdate();
        query.close();
    }

    public static QueryTableModel getTableModel() {
        String sql = "select *  from aluno";
        DataBase conn = DataBase.getInstance();
        QueryTableModel qtm = new QueryTableModel(conn, sql);
        return qtm;
    }
}

FichaAluno

package GUI;

import classesNegocios.Aluno;
import classesNegocios.Usuario;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;



/**
 *
 * @author aluno
 */
public class FichaAluno extends javax.swing.JDialog {

    private int result = 0;
    private Aluno aluno = new Aluno();
    

    /**
     * Creates new form FichaAluno
     */
    public FichaAluno(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        setResult(1);
        setVisible(false);
}                                        
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

      
        if ((jTextField1.getText().isEmpty()) || (jTextField2.getText().isEmpty())
                || (jTextField3.getText().isEmpty()) || (jTextField4.getText().isEmpty())
                || (jTextField5.getText().isEmpty()) || (jTextField6.getText().isEmpty())
                || (jTextField7.getText().isEmpty()) || (jTextField8.getText().isEmpty())
                || (jTextField9.getText().isEmpty()) ) {

            JOptionPane.showMessageDialog(null, "Existem campos inválidos.", "Informação do Sistema", JOptionPane.WARNING_MESSAGE, new ImageIcon(getClass().getResource("/imagens/info.png")));

             } else {

            aluno.setNome(jTextField1.getText());
            aluno.setCpf(jTextField2.getText());
            aluno.setDtnascimento(jTextField3.getText());
            aluno.setTelefone(jTextField4.getText());
            aluno.setEndereco(jTextField5.getText());
            aluno.setCep(jTextField6.getText());
            aluno.setEmail(jTextField7.getText());
            aluno.setDtmatricula(jTextField8.getText());
            aluno.setTipo(jTextField9.getText());
            setResult(0);
            setVisible(false);

            JOptionPane.showMessageDialog(this, "Aluno " + jTextField1.getText() + " inserido com sucesso!","Informação do Sistema", JOptionPane.OK_OPTION,new ImageIcon(getClass().getResource("/imagens/good.png")));
        }


}                                        

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

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        jTextField1.setText("");
        jTextField2.setText("");
        jTextField3.setText("");
        jTextField4.setText("");
        jTextField5.setText("");
        jTextField6.setText("");
        jTextField7.setText("");
        jTextField8.setText("");
        jTextField9.setText("");

    }                                        

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

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

    private void jTextField2FocusLost(java.awt.event.FocusEvent evt) {                                      
        // TODO add your handling code here:
        if (!jTextField2.getText().contains("_")) {
            if (!util.Utils.validaCPF(jTextField2.getText())) {
                jTextField2.setForeground(Color.RED);
                JOptionPane.showMessageDialog(null, "CPF inválido!",
                        "Informação do Sistema", JOptionPane.ERROR_MESSAGE,new ImageIcon(getClass().getResource("/imagens/erro.png")));

            } else {
                jTextField2.setForeground(Color.BLUE);
            }
        }

    }                                     

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

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FichaAluno dialog = new FichaAluno(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    /**
     * @return the result
     */
    public int getResult() {
        return result;
    }

    /**
     * @param result the result to set
     */
    public void setResult(int result) {
        this.result = result;
    }

    /**
     * @return the aluno
     */
    public Aluno getAluno() {
        return aluno;
    }

    /**
     * @param aluno the aluno to set
     */
    public void setAluno(Aluno aluno) {
        this.aluno = aluno;
        jTextField1.setText(aluno.getNome());
        jTextField2.setText(aluno.getCpf());
        jTextField3.setText(aluno.getDtnascimento());
        jTextField4.setText(aluno.getTelefone());
        jTextField5.setText(aluno.getEndereco());
        jTextField6.setText(aluno.getCep());
        jTextField7.setText(aluno.getEmail());
        jTextField8.setText(aluno.getDtmatricula());
        jTextField9.setText(aluno.getTipo());


    }

    void setAluno(Usuario a) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

FormAluno

package GUI;

import classesNegocios.Aluno;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


public class FrmAluno extends javax.swing.JFrame {

   
    public FrmAluno() {
        initComponents();
        jTable1.setModel(Aluno.getTableModel());

    }

    
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        int linhaSelecionada = jTable1.getSelectedRow();
        if (linhaSelecionada != -1) {//Verifica se existe linha selecionada
            String matricula = (String) jTable1.getModel().getValueAt(linhaSelecionada, 0);
            String nome = (String) jTable1.getModel().getValueAt(linhaSelecionada, 1);
            int resposta = JOptionPane.showConfirmDialog(this, "Confirma EXCLUSÃO do aluno: " + nome);
            if (resposta == JOptionPane.YES_OPTION) {
                //String sql = "delete from aluno where matricula = " + matricula;
                //bd.atualizaSql(sql);
                Aluno a = new Aluno();
                a.setMatricula(Integer.parseInt(matricula));
                try {
                    a.delete();
                } catch (SQLException ex) {
                    Logger.getLogger(FrmAluno.class.getName()).log(Level.SEVERE, null, ex);
                }
                jTable1.setModel(Aluno.getTableModel());

            }
        }
}                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        int linhaSelecionada = jTable1.getSelectedRow();
        if (linhaSelecionada != -1) {//se existe alguma linha selecionada faça:
            //Captura os dados da linha selecionada no jTable1
            String matricula = (String) jTable1.getModel().getValueAt(linhaSelecionada, 0);
            String nome = (String) jTable1.getModel().getValueAt(linhaSelecionada, 1);
            String cpf = (String) jTable1.getModel().getValueAt(linhaSelecionada, 2);
            String dtnascimento = (String) jTable1.getModel().getValueAt(linhaSelecionada, 3);
            String telefone = (String) jTable1.getModel().getValueAt(linhaSelecionada, 4);
            String endereco = (String) jTable1.getModel().getValueAt(linhaSelecionada, 5);
            String cep = (String) jTable1.getModel().getValueAt(linhaSelecionada, 6);
            String email = (String) jTable1.getModel().getValueAt(linhaSelecionada, 7);
            String dtmatricula = (String) jTable1.getModel().getValueAt(linhaSelecionada, 8);
            String tipo = (String) jTable1.getModel().getValueAt(linhaSelecionada, 9);

            //cria um objeto da classe Aluno, e seta os dados selecionados
            Aluno a = new Aluno();
            a.setMatricula(Integer.parseInt(matricula));
            a.setNome(nome);
            a.setCpf(cpf);
            a.setDtnascimento(dtnascimento);
            a.setTelefone(telefone);
            a.setEndereco(endereco);
            a.setCep(cep);
            a.setEmail(email);
            a.setDtmatricula(dtmatricula);
            a.setTipo(tipo);
            //Instancia o diálogo FichaAluno
            FichaAluno fs = new FichaAluno(this, true);
            fs.setAluno(a); //transfere os dados do objeto "a" (Aluno) para o diálogo
            fs.setVisible(true);//Exibe o diálogo FichaAluno
            if (fs.getResult() == 0) { // Se o botão [Confimar] foi pressionado
                try { //Início de bloco protegido
                    a = fs.getAluno(); //"pega" os dados que foram preenchidos no diálogo
                    a.update(); // Atualiza os dados no banco de dados
                } catch (SQLException ex) { //Caso ocorra algum erro de execussão faça:
                    JOptionPane.showMessageDialog(this,
                            "Ocorreu um erro ao tentar executar SQL\n" + ex.getMessage());
                }
                jTable1.setModel(Aluno.getTableModel()); //atualiza a visualização do jtable.
            }
        } else {//O usuário NÃO selecionou nenhuma linha
            JOptionPane.showMessageDialog(this, "É necessário selecionar uma linha da tabela para edição");
        }
}                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        FichaAluno aut = new FichaAluno(this, true);
        aut.setVisible(true);
        if (aut.getResult() == 0) {
            try {
                aut.getAluno().insert();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Erro ao tentar incluir aluno!");
            }
            jTable1.setModel(Aluno.getTableModel());
        }
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        setVisible(false);
}                                        
    public void atualizaTextArea() {
        int linhaSelecionada = jTable1.getSelectedRow();
        if (linhaSelecionada != -1) {//se existe alguma linha selecionada faça:
            //Captura os dados da linha selecionada no jTable1
            String matricula = (String) jTable1.getModel().getValueAt(linhaSelecionada, 0);
            String nome = (String) jTable1.getModel().getValueAt(linhaSelecionada, 1);
            String cpf = (String) jTable1.getModel().getValueAt(linhaSelecionada, 2);
            String dtnascimento = (String) jTable1.getModel().getValueAt(linhaSelecionada, 3);
            String telefone = (String) jTable1.getModel().getValueAt(linhaSelecionada, 4);
            String endereco = (String) jTable1.getModel().getValueAt(linhaSelecionada, 5);
            String cep = (String) jTable1.getModel().getValueAt(linhaSelecionada, 6);
            String email = (String) jTable1.getModel().getValueAt(linhaSelecionada, 7);
            String dtmatricula = (String) jTable1.getModel().getValueAt(linhaSelecionada, 8);
            String tipo = (String) jTable1.getModel().getValueAt(linhaSelecionada, 9);

            //Visualizar linhas

            jTextArea1.setText("MATRICULA: "  + matricula + "\n"
                    + "NOME: " +  nome + "\n"
                    + "CPF: " +  cpf + "\n"
                    + "DATA DE NASCIMENTO: " +  dtnascimento + "\n"
                    + "TELEFONE: " +  telefone + "\n"
                    + "ENDEREÇO: " +  endereco + "\n"
                    + "CEP: " + cep + "\n"
                    + "E-MAIL: " +  email + "\n"
                    + "DATA DE MATRICULA: " +  dtmatricula + "\n"
                    + "CURSO: " +  tipo); 

        }

    }

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

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

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {                                   
        // TODO add your handling code here:
        atualizaTextArea();
    }                                  

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        atualizaTextArea();
    }                                    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmAluno().setVisible(true);
            }
        });
    }
                   
}

13 Respostas

fabiocortolan

Pelo q entendi vc está utilizando o Date de “java.sql.Date” mas o componente utiliza “java.util.Date”, nesse caso na sua classe Aluno vc deve utilizar o “java.util.Date” e qdo for persistir os dados fazer a conversão para “java.sql.Date”.

E
[size=14]Fabiocortolan , obrigado por me responder, eu fiz o que você me disse que aparece essa mensagem de erro:

[/size]

Exception in thread AWT-EventQueue-0 java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

at classesDAO.AlunoDAO.insert(AlunoDAO.java:35)

at classesNegocios.Aluno.insert(Aluno.java:31)

at GUI.FrmAluno.jButton3ActionPerformed(FrmAluno.java:283)

at GUI.FrmAluno.access$300(FrmAluno.java:24)

at GUI.FrmAluno$4.actionPerformed(FrmAluno.java:86)

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

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

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:6505)

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

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

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

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

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

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

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

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

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

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

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

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

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

at java.awt.EventQueue.access$200(EventQueue.java:103)

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

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

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

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)

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

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

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

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)

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

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

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

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

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

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

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

[size=14]Está ocorrendo esse erro quando eu vou inserir um aluno.

Na Classe Aluno alterei o dtnascimento para Date e usei import java.util.Date :[/size]

import java.util.Date;

public class Aluno {
private Date dtnascimento;

  
    public Date getDtnascimento() {
        return dtnascimento;
    }

        public void setDtnascimento(Date dtnascimento) {
        this.dtnascimento = dtnascimento;
    }
}

[size=14]Na classe AlunoDAO, que é aonde está ocorrendo o problema fiz: ao usar o SetDate deu erro na linha e pediu para converter dtnascimento em Date assim ele usou (java.sql.Date).
[/size]

public void insert() throws SQLException {
query.setDate(3, (java.sql.Date) aluno.getDtnascimento());

public void update() throws SQLException {
query.setDate(3, (java.sql.Date) aluno.getDtnascimento());

[size=14]Nesse caso o que eu faço?[/size]

fabiocortolan

Qual o tipo de dados do campo data da sua tabela?
Se for timestamp vc pode usar o comando abaixo para converter:

Timestamp dataSql = new Timestamp(aluno.getDtnascimento());
query.setDate(3, dataSql);

// ou fazer a conversão direto na query:
// query.setDate(3, new Timestamp(aluno.getDtnascimento());

Se vc precisar converter em java.sql.Date mesmo, use o método “getTime()” para a conversão no construtor do sql.Date:

query.setDate(3, new java.sql.Date(aluno.getDtnascimento().getTime()));

Não fiz os testes mas acho q dessa forma vai resolver.

E

Eu utilizei o :

query.setDate(3, new java.sql.Date(aluno.getDtnascimento().getTime()));

Agora ele da Erro ao Tentar incluir Aluno:Nesse Evento que ocorre essa mensagem

FichaAluno aut = new FichaAluno(this, true);
        aut.setVisible(true);
        if (aut.getResult() == 0) {
            try {
                aut.getAluno().insert();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Erro ao tentar incluir aluno!");
            }
            jTable1.setModel(Aluno.getTableModel());
        }
    }

E sobre o tipo de dado que eu utilizei no campo data da sua tabela foi DATE.Poderia ter usado esse tipo?

fabiocortolan

Posta o erro q está ocorrendo (ex.printStackTrace()), assim fica mais fácil.
Sobre o tipo de campo na tabela, não sou um expert em banco de dados mas depende do q vc precisa, eu prefiro usar timestamp no postgresql, se vc usa apenas a data, acredito q não tenha problema nesse tipo de campo.

E

Não aparece nenhum erro na linha só a mensagem “Erro ao Tentar Incluir Aluno” dessa condição:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        FichaAluno aut = new FichaAluno(this, true);
        aut.setVisible(true);
        if (aut.getResult() == 0) {
            try {
                aut.getAluno().insert();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Erro ao tentar incluir aluno!");
            }
            jTable1.setModel(Aluno.getTableModel());
        }
    }

Agora complicou.Erro todo está ao inserir.

Bruno.Souza.PW

coloca assim…

} catch (SQLException ex) {  
                JOptionPane.showMessageDialog(null, "Erro ao tentar incluir aluno!");  
                System.out.println(ex.getMessage());  
}

e posta o erro que esta acontecendo…

E

A parte de inserir creio que tenha resolvido com ajuda do fabiocortolan, só agora está ocorrendo outro erro:
Exception in thread “AWT-EventQueue-0” java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
at GUI.FrmAluno.jButton4ActionPerformed(FrmAluno.java:238)

Nessa Linha:

Date dtnascimento = (Date) jTable1.getModel().getValueAt(linhaSelecionada, 3);

E agora o que pode ter acontecido para ocorrer esse erro?

fabiocortolan

Novamente é problema na conversão, dessa vez de String para Date(), dá uma olhada no post abaixo q explica como fazer a conversão:
http://www.guj.com.br/java/41935-converter-string-para-date

Obs.: fique atento com essas conversões, a maior parte dos seus problemas foram na hora de converter um tipo de dado para outro :wink: !

E

fabiocortolan , olhei o post achei muito útil , só usando esse código abaixo na classe aluno para conversão.

/** 
         * Converte uma String para um objeto Date. Caso a String seja vazia ou nula,  
         * retorna null - para facilitar em casos onde formulários podem ter campos 
         * de datas vazios. 
         * @param data String no formato dd/MM/yyyy a ser formatada 
         * @return Date Objeto Date ou null caso receba uma String vazia ou nula 
         * @throws Exception Caso a String esteja no formato errado 
         */  
        public static Date formataData(String data) throws Exception {   
            if (data == null || data.equals(""))  
                return null;  
              
            Date date = null;  
            try {  
                DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");  
                date = (java.util.Date)formatter.parse(data);  
            } catch (ParseException e) {              
                throw e;  
            }  
            return date;  
        }

Como eu chamo ele na linha que está ocorrendo erro?

Nessa: Date dtnascimento = (Date) jTable1.getModel().getValueAt(linhaSelecionada, 3);

Estou muito perdido nessas conversões. :cry: :cry:
Obrigado pela ajuda.

fabiocortolan

Instancia a classe DateFormatter em alguma parte do seu código e depois faz o parse na hora d atribuir o valor à variável dtnasimento:

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");      
Date dtnascimento = (Date) formatter.parse(jTable1.getModel().getValueAt(linhaSelecionada, 3));

Tome cuidado apenas com o formato da data qdo instanciar o SimpleDateFormat.
:idea: Uma dica, use camel case para nomes de variáveis, é uma boa prática e ajuda a ler as variáveis mais facilmente, no seu caso “dtNascimento” com o N maiúsculo!

E

Utilizei :

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");        
Date dtnascimento = (Date) formatter.parse(jTable1.getModel().getValueAt(linhaSelecionada, 3));

Só aparece um erro na linha:

Date dtnascimento = (Date) formatter.parse(jTable1.getModel().getValueAt(linhaSelecionada, 3));

E pede para: “Conveter…getValueAt(…) em String”. converti só que mesmo assim apareceu outro que diz:
unreported exception ParseException; must be caught or declared to be thorown
com opção de: Circundar Instrução com try-catch: que fica assim:

Date dtnascimento; try { dtnascimento = (Date) formatter.parse((String) jTable1.getModel().getValueAt(linhaSelecionada, 3)); } catch (ParseException ex) { Logger.getLogger(FrmAluno.class.getName()).log(Level.SEVERE, null, ex); }
Logo depois pede para da erro na variável dtnascimento e pede para Inicializar variável dtnascimento, ficando assim com null.

date dtnascimento = null; try { dtnascimento = (Date) formatter.parse((String) jTable1.getModel().getValueAt(linhaSelecionada, 3)); } catch (ParseException ex) { Logger.getLogger(FrmAluno.class.getName()).log(Level.SEVERE, null, ex); }
Quando vou visualizar os dados a Data e mostrada como Null e no Banco de dados foi inserida ao contrario “YYYY/MM/DD”

E aparece esse erro:

run:

Conexão realizada com sucesso!

Mar 26, 2013 3:42:39 PM GUI.FrmAluno atualizaTextArea

SEVERE: null

java.text.ParseException: Unparseable date: 2013-03-04

at java.text.DateFormat.parse(DateFormat.java:357)

at GUI.FrmAluno.atualizaTextArea(FrmAluno.java:312)

at GUI.FrmAluno.jTable1MouseClicked(FrmAluno.java:355)

at GUI.FrmAluno.access$400(FrmAluno.java:27)

at GUI.FrmAluno$5.mouseClicked(FrmAluno.java:111)

at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

at java.awt.EventQueue.access$200(EventQueue.java:103)

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

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

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

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)

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

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

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

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)

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

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

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

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

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

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

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

tela:

O que pode ser isso agora? Será que a conversão para String não está funcionando?

fabiocortolan

Parece q o problema agora é a conversão do banco para o objeto, tente fazer o mesmo esquema do DateFormatter qdo vc for preencher a variável dtnascimento com a data q vc pega do banco.

Criado 26 de março de 2013
Ultima resposta 26 de mar. de 2013
Respostas 13
Participantes 3