MEU PROJETO TEM 3 CLASSES FUNCIONARIO, EMPRESA, SEÇÃO
FUNCIONARIO É A PRINCIPAL , EMPRESA E SEÇÃO TENHO UM BOTÃO INCLUIR QUE QUERO ACESSAR O BANCO TAMBEM COMO FAÇO?
QUANDO COMPILA ELE DA ERRO DE BANCO DE DADOS NO STATEMENT DAS QUERY PARA UPDATE,INSERT,DELETE
ALGUEM PODE ME AJUDAR AGORA POSTEI CORRETAMENTE O CODIGO
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
public class Funcionario extends JFrame implements ActionListener
{
ResultSet resultset;//classe usada para armazenar o resultado gerado pelo comando SQL
Statement statement;//permite executar um comando SQL que será usado no programa
private JButton btConsultar,btIncluir,btAlterar, btDeletar,btLimpar;
private JMenuItem Consultar,Incluir,Alterar,Deletar;
private JTextField tfcodigo,tfempresa ,tfdepto,tfcargo,tfsecao,tfnome ,tfjornada,tfdatanasc,tfdataadm;
public static void main(String[] args)
{
JFrame janela = new Funcionario();//
janela.setUndecorated(true);
janela.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//responsável por sair da aplicação quando a janela for fechada
janela.setVisible(true);//deixa a janela visivel
}
public Funcionario()
{
JMenuBar barraMenu =new JMenuBar();
this.setJMenuBar(barraMenu);
JMenu menuMenu =new JMenu("Menu");
menuMenu.setMnemonic('M');
barraMenu.add(menuMenu);
menuMenu.add(new JSeparator());
JMenuItem empItem =new JMenuItem ("Empresa");
empItem.addActionListener(this);//registra o objeto para que o evento gerado por ele seja reconhecido
menuMenu.add(empItem);
menuMenu.add(new JSeparator());
JMenuItem secItem =new JMenuItem ("Seção");
secItem.addActionListener(this);//registra o objeto para que o evento gerado por ele seja reconhecido
menuMenu.add(secItem);
menuMenu.add(new JSeparator());
JMenuItem sairItem =new JMenuItem ("Sair");
sairItem.addActionListener(this);//registra o objeto para que o evento gerado por ele seja reconhecido
menuMenu.add(sairItem);
menuMenu.add(new JSeparator());
JMenu opcoesMenu = new JMenu("Opções");
opcoesMenu.setMnemonic('O');
barraMenu.add(opcoesMenu);
Consultar = new JMenuItem("Consultar");
Consultar.addActionListener(this);//registra o objeto para que o evento gerado por ele seja reconhecido
opcoesMenu.add(Consultar);
Incluir = new JMenuItem("Incluir");
Incluir.addActionListener(this);//registra o objeto para que o evento gerado por ele seja reconhecido
opcoesMenu.add(Incluir);
Alterar = new JMenuItem("Alterar");
Alterar.addActionListener(this);//registra o objeto para que o evento gerado por ele seja reconhecido
opcoesMenu.add(Alterar);
Deletar = new JMenuItem("Deletar");
Deletar.addActionListener(this);//registra o objeto para que o evento gerado por ele seja reconhecido
opcoesMenu.add(Deletar);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension desktop = tk.getScreenSize();
this.setSize(desktop.width,desktop.height -30);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel label = new JLabel();
label = new JLabel("EMPRESA");
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(50,30,0,0);// cima,baixo,direita,esquerda
c.fill = GridBagConstraints.BOTH; // redimesionar o componente
c.anchor = GridBagConstraints.CENTER;
panel.add(label, c);
tfempresa = new JTextField("");
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(50,30,0,0);
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(tfempresa, c);
label = new JLabel("CODIGO");
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(50,0,50,10);
c.fill = GridBagConstraints.LINE_START;
panel.add(label, c);
tfcodigo = new JTextField(" ");
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(50,0,50,50);
c.fill = GridBagConstraints.REMAINDER;
panel.add(tfcodigo, c);
label = new JLabel("DEPARTAMENTO");
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(0,0,0,10);
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(label, c);
tfdepto = new JTextField("");
c.gridheight = 1;
c.insets = new Insets(0,0,0,10);
c.gridwidth = GridBagConstraints.NONE;
panel.add(tfdepto, c);
label = new JLabel("CARGO");
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(0,50,0,0);
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(label, c);
tfcargo = new JTextField("");
c.insets = new Insets(0,10,0,0);
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(tfcargo, c);
label = new JLabel("JORNADA TRABALHO");
c.insets = new Insets(30,30,0,0);
c.fill= GridBagConstraints.HORIZONTAL;
panel.add(label, c);
tfjornada = new JTextField("");
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(0,0,0,0);
c.gridwidth = GridBagConstraints.NORTH;
panel.add(tfjornada, c);
label = new JLabel("SEÇÃO");
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(0,50,0,0);
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(label, c);
tfsecao = new JTextField(" ");
c.insets = new Insets(0,10,0,50);
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(tfsecao, c);
label = new JLabel("NOME");
c.insets = new Insets(30,30,0,0);// cima, baixo, direita, esquerda
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.NONE;
panel.add(label, c);
tfnome = new JTextField("");
c.insets = new Insets(0,0,0,0);
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(tfnome, c);
label = new JLabel("DATA ADMISSÃO");
c.insets = new Insets(30,200,0,0);
c.gridwidth = GridBagConstraints.NORTHEAST;
panel.add(label, c);
tfdataadm = new JTextField("");
c.insets = new Insets(30,0,0,0);
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(tfdataadm, c);
label = new JLabel("DATA NASCIMENTO");
c.insets = new Insets(30,200,0,0);
c.gridwidth = GridBagConstraints.NORTHEAST;
panel.add(label, c);
tfdatanasc = new JTextField(" ");
c.insets = new Insets(30,0,0,0);
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(tfdatanasc, c);
JPanel rodape = new JPanel();
btConsultar = new JButton("Consultar");
btConsultar.addActionListener(this);
rodape.add(btConsultar);
btIncluir = new JButton("Incluir");
btIncluir.addActionListener(this);
rodape.add(btIncluir);
btAlterar = new JButton("Alterar");
btAlterar.addActionListener(this);
rodape.add(btAlterar);
btDeletar = new JButton("Deletar");
btDeletar.addActionListener(this);
rodape.add(btDeletar);
btLimpar = new JButton("Limpar");
btLimpar.addActionListener(this);
rodape.add(btLimpar);
JButton btnSair =new JButton("Sair");
btnSair.addActionListener(this);
rodape.add(btnSair);
this.getContentPane().add(rodape, BorderLayout.SOUTH);// adiciona componentes a frame
this.getContentPane().add(panel, BorderLayout.NORTH);// adiciona componentes a frame
rodape.setBorder(BorderFactory.createEtchedBorder());// cria uma borda no painel
panel.setVisible(true);
setTitle("Cadastro Funcionário"); // nomeia o titulo da tela
}
public void carregaResultSet()
{
String url = "jdbc:odbc:MeuBanco";//string que armazena o endereço da localização do banco de dados
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection minhaConexao = DriverManager.getConnection(url);//carrega o driver que será usado pela aplicação para realizar a comunicação com o banco de dados
statement =minhaConexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
//permite a inicialização de um objeto para a execução de comandos SQL/navegação nos dois sentidos/somente leitura
resultset = statement.executeQuery("SELECT * FROM funcionario");//armazena o resultado gerado pelo comando SQL
setBotoes(true,true,true,true,true);
}
catch (ClassNotFoundException erro)//caso o driver não seja localizado
{
System.out.println("Driver JDBC-ODBC não encontrado");
}
catch (SQLException erro)//caso a conexão não possa ser realizada por qualquer motivo
{
System.out.println("Problemas de conexão com a fonte de dados");
}
}
public void setBotoes(boolean bConsultar, boolean bIncluir, boolean bAlterar, boolean bDeletar,
boolean bLimpar)
{
btConsultar.setEnabled(bConsultar);
btIncluir.setEnabled(bIncluir);
btAlterar.setEnabled(bAlterar);
btDeletar.setEnabled(bDeletar);
btLimpar.setEnabled(bLimpar);
}
public void actionPerformed(ActionEvent ae)
{
try
{
if(ae.getActionCommand().equalsIgnoreCase("Empresa"))
{
Empresa.addActionListener ( new Empresa());
}
{
if(ae.getActionCommand().equalsIgnoreCase("Seção"))
{
Secao.addActionListener ( new Secao());
}
}
{
if (ae.getSource()==btIncluir)
{
String sql = "INSERT INTO funcionario(codigo,empresa,departamento,secao,jornada,cargo,nome,datanasc,dataadm)Values('"+
"Empresa = '" + tfempresa.getText() + "',"+
"Codigo = '" + tfcodigo.getText() + "',"+
"Departamento = '" + tfdepto.getText() + "',"+
"Seção = '" + tfsecao.getText() + "',"+
"Cargo = '" + tfcargo.getText() + "',"+
"Jornada = '" + tfjornada.getText() + "',"+
"Nome = '" + tfnome.getText() + "',"+
"Data Nascimento = '" + tfdatanasc.getText() + "'"+
"Data Admissão = '" + tfdataadm.getText() + "')";
statement.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"Gravação realizada com sucesso!");
setBotoes(true,true,true,true,true);
}
}
}
catch (SQLException erro)
{
if (erro.getMessage().equals("General error"))
JOptionPane.showMessageDialog(null,"Funcionário já cadastrado");
else
JOptionPane.showMessageDialog(null,"Data Inválida");
}
carregaResultSet();
if (ae.getSource()==btAlterar)
{
try
{
String sql = "Update funcionario SET " +
"Empresa = '" + tfempresa.getText() + "',"+
"Codigo = '" + tfcodigo.getText() + "',"+
"Departamento = '" + tfdepto.getText() + "',"+
"Seção = '" + tfsecao.getText() + "',"+
"Cargo = '" + tfcargo.getText() + "',"+
"Jornada = '" + tfjornada.getText() + "',"+
"Nome = '" + tfnome.getText() + "',"+
"Data Nascimento = '" + tfdatanasc.getText() + "'"+
"Data Admissão = '" + tfdataadm.getText() + "')";
int r = statement.executeUpdate(sql);
if (r==1)
JOptionPane.showMessageDialog(null,"Inclusão realizada com sucesso!");
else
JOptionPane.showMessageDialog(null,"Problemas na Inclusão");
setBotoes(true,true,true,true,true);
}
catch(SQLException erro)
{
JOptionPane.showMessageDialog(null,"Data inválida");
}
carregaResultSet();
}
if (ae.getSource()==btDeletar)
{
try
{
String sql = "SELECT codigo,nome,secao,empresa FROM funcionario Where codigo = '"+tfcodigo.getText()+"'";
resultset = statement.executeQuery(sql);
String funcionario = "";
try
{
resultset.next();
funcionario = "Deletar o Funcionário: "+resultset.getString("Funcionário");
}
catch(SQLException EX1 )
{
JOptionPane.showMessageDialog(null,"Funcionário não cadastrado!");
carregaResultSet();
return;
}
int n=
JOptionPane.showConfirmDialog(null,funcionario,"",JOptionPane.YES_NO_OPTION);
if (n==JOptionPane.YES_OPTION);
{
sql = "DELETE FROM funcionario Where codigo = '" + tfcodigo.getText() + "'";
int r = statement.executeUpdate(sql);
if (r==1)
JOptionPane.showMessageDialog(null,"Exclusão realizada com sucesso!");
else
JOptionPane.showMessageDialog(null,"Não foi possível excluir o Funcionário");
LimpaCampos();
setBotoes(true,true,true,true,true);
}
}
catch(SQLException erro)
{
JOptionPane.showMessageDialog(null,"problemas...");
}
}
{
if(ae.getActionCommand().equalsIgnoreCase("Sair"))
{
// int opcao;
// opcao=JOptionPane.showConfirmDialog(null,"Deseja realmente sair?","Sair",JOptionPane.YES_NO_OPTION);
// if (opcao==JOptionPane.YES_OPTION)
System.exit(0);
}
}
if (ae.getSource()==btLimpar)
{
LimpaCampos();
}
}
public void LimpaCampos()
{
tfempresa.setText("");
tfcodigo.setText("");
tfdepto.setText("");
tfsecao.setText("");
tfcargo.setText("") ;
tfjornada.setText("");
tfnome.setText("");
tfdatanasc.setText("");
tfdataadm.setText("");
}
}