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);
}
});
}
}