Boa tarde galera,
estou com problemas paranavegar no banco.
Bom, dei uma olhada pelo fórum para ver se achava alguma dúvida igual e encontrei várias, porém, ainda assim não consegui achar meu erro.
Segue o código.
package tela;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.text.MaskFormatter;
import dadosCliente.Cliente;
import db.ContataDAO;
public class interfaceGrafica extends JFrame{
private JLabel lCpf,lNome,lCargo,lSalario,lCodigo;
private JTextField tfNome,tfCargo,tfSalario,tfCodigo;
private JFormattedTextField tfCpf;
private JButton btGravar,btMostrar,btAlterar,btLimpar,btExcluir,btSair,btPrimeiro,btUltimo,btAnterior,btPosterior;
private JPanel tela1,tela2,tela3;
Cliente cliente = new Cliente();
ContataDAO contataDAO = new ContataDAO();
public interfaceGrafica()
{
lCpf = new JLabel("CPF");
try {
tfCpf = new JFormattedTextField(new MaskFormatter("###.###.###-##"));
} catch (ParseException e1) {
e1.printStackTrace();
}
lNome = new JLabel("Nome");
tfNome = new JTextField(15);
lCargo = new JLabel("Cargo");
tfCargo = new JTextField(15);
lSalario = new JLabel("Salario");
tfSalario = new JTextField(15);
lCodigo = new JLabel("Codigo");
tfCodigo = new JTextField(5);
btGravar = new JButton("Gravar");
btMostrar = new JButton("Mostrar");
btAlterar = new JButton("Alterar");
btLimpar = new JButton("Limpar");
btExcluir = new JButton("Excluir");
btSair = new JButton("Sair");
btPrimeiro = new JButton("<<");
btUltimo = new JButton(">>");
btAnterior = new JButton("<");
btPosterior = new JButton(">");
tela1 = new JPanel(new GridLayout(6,2));
tela2 = new JPanel(new GridLayout(2,3));
tela3 = new JPanel(new GridLayout(0,4));
tela1.add(lCodigo);
tela1.add(tfCodigo);
tela1.add(lCpf);
tela1.add(tfCpf);
tela1.add(lNome);
tela1.add(tfNome);
tela1.add(lCargo);
tela1.add(tfCargo);
tela1.add(lSalario);
tela1.add(tfSalario);
tela2.add(btGravar);
tela2.add(btMostrar);
tela2.add(btAlterar);
tela2.add(btLimpar);
tela2.add(btExcluir);
tela2.add(btSair);
tela3.add(btPrimeiro);
tela3.add(btAnterior);
tela3.add(btPosterior);
tela3.add(btUltimo);
this.add("North",tela1);
this.add("South",tela2);
this.add("Center",tela3);
this.pack();
this.setVisible(true);
this.setResizable(false);
btPrimeiro.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ResultSet resultado = contataDAO.Navegar();
try{
resultado.first();
tfCodigo.setText(resultado.getInt("codigo")+"");
tfCpf.setText(resultado.getString("cpf"));
tfNome.setText(resultado.getString("nome"));
tfCargo.setText(resultado.getString("cargo"));
tfSalario.setText(resultado.getFloat("salario")+"");
}catch(SQLException e){
JOptionPane.showMessageDialog(interfaceGrafica.this, "Primeiro");
}finally{
try {
resultado.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
});
btAnterior.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ResultSet resultado = contataDAO.Navegar();
try{
resultado.previous();
tfCodigo.setText(resultado.getInt("codigo")+"");
tfCpf.setText(resultado.getString("cpf"));
tfNome.setText(resultado.getString("nome"));
tfCargo.setText(resultado.getString("cargo"));
tfSalario.setText(resultado.getFloat("salario")+"");
}catch(SQLException e){
JOptionPane.showMessageDialog(interfaceGrafica.this, "Este é o primeiro registro.");
}
}
});
btPosterior.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ResultSet resultado = contataDAO.Navegar();
try{
resultado.next();
tfCodigo.setText(resultado.getInt("codigo")+"");
tfCpf.setText(resultado.getString("cpf"));
tfNome.setText(resultado.getString("nome"));
tfCargo.setText(resultado.getString("cargo"));
tfSalario.setText(resultado.getFloat("salario")+"");
}catch(SQLException e){
JOptionPane.showMessageDialog(interfaceGrafica.this, "Este é o último registro.");
}
}
});
btUltimo.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ResultSet resultado = contataDAO.Navegar();
try{
resultado.last();
tfCodigo.setText(resultado.getInt("codigo")+"");
tfCpf.setText(resultado.getString("cpf"));
tfNome.setText(resultado.getString("nome"));
tfCargo.setText(resultado.getString("cargo"));
tfSalario.setText(resultado.getFloat("salario")+"");
}catch(SQLException e){
JOptionPane.showMessageDialog(interfaceGrafica.this, "Último");
}finally{
try {
resultado.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
});
btGravar.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cliente.setCpf(tfCpf.getText());
cliente.setNome(tfNome.getText());
cliente.setCargo(tfCargo.getText());
cliente.setSalario(Float.parseFloat(tfSalario.getText()));
contataDAO.adiciona(cliente);
tfCodigo.setText(null);
tfCpf.setText(null);
tfNome.setText(null);
tfCargo.setText(null);
tfSalario.setText(null);
}
});
btMostrar.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int codigo = Integer.parseInt(tfCodigo.getText());
Cliente cliente;
cliente = contataDAO.buscarUnico(codigo);
if(cliente != null){
tfCpf.setText(cliente.getCpf()+"");
tfNome.setText(cliente.getNome());
tfCargo.setText(cliente.getCargo());
tfSalario.setText(cliente.getSalario()+"");
}else{
tfCodigo.setText(null);
tfCpf.setText(null);
tfNome.setText(null);
tfCargo.setText(null);
tfSalario.setText(null);
JOptionPane.showMessageDialog(interfaceGrafica.this, "Não Existe Cliente Com o Código "+codigo,
"Código Inválido", JOptionPane.WARNING_MESSAGE);
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(interfaceGrafica.this,
"Opa, Somente Números é Válido!",
"Código Inválido", JOptionPane.WARNING_MESSAGE);
} catch (SQLException e) {
JOptionPane.showMessageDialog(interfaceGrafica.this,
"Erro Com o Banco de Dados\nErro: "+e.getMessage(),
"Erro com o Banco de Dados", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
});
btAlterar.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cliente.setCodigo(Integer.parseInt(tfCodigo.getText()));
cliente.setCpf(tfCpf.getText());
cliente.setNome(tfNome.getText());
cliente.setCargo(tfCargo.getText());
cliente.setSalario(Float.parseFloat(tfSalario.getText()));
contataDAO.altera(cliente);
}
});
btLimpar.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
tfCodigo.setText(null);
tfCpf.setText(null);
tfNome.setText(null);
tfCargo.setText(null);
tfSalario.setText(null);
}
});
btExcluir.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cliente.setCodigo(Integer.parseInt(tfCodigo.getText()));
contataDAO.excluir(cliente);
}
});
btSair.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
contataDAO.desconectar();
System.exit(0);
}
});
}
}
package db;
import java.sql.*;
import dadosCliente.Cliente;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class ContataDAO {
private Connection con;
Cliente cliente = new Cliente();
public ContataDAO() {
try {
con = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/teste", "postgres",
"122222");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void adiciona(Cliente cliente) {
try {
PreparedStatement stmt = con.prepareStatement("insert into contato (cpf,nome,cargo,salario) values (?,?,?,?)");
// prepared statement para inserção
// seta os valores
stmt.setString(1, cliente.getCpf());
stmt.setString(2, cliente.getNome());
stmt.setString(3, cliente.getCargo());
stmt.setFloat(4, cliente.getSalario());
// executa
stmt.executeUpdate();
stmt.close();
JOptionPane.showMessageDialog(null,"Cadastro adicionado com sucesso!");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Cliente buscarUnico(int codigo) throws SQLException{
PreparedStatement ps = con.prepareStatement("SELECT * FROM contato WHERE codigo=?");
ps.setInt(1, codigo);
ps.execute();
ResultSet rs = ps.getResultSet();
if(rs.next()){
Cliente cliente = new Cliente();
cliente.setCpf(rs.getString("cpf"));
cliente.setNome(rs.getString("nome"));
cliente.setCargo(rs.getString("cargo"));
cliente.setSalario(rs.getFloat("salario"));
cliente.setCodigo(rs.getInt("codigo"));
return cliente;
}else{
return null;
}
}
public void altera(Cliente cliente) {
try {
PreparedStatement stmt = con.prepareStatement("update contato set cpf=?, nome=?, cargo=?, salario=? where codigo=?");
stmt.setString(1, cliente.getCpf());
stmt.setString(2, cliente.getNome());
stmt.setString(3, cliente.getCargo());
stmt.setFloat(4, cliente.getSalario());
stmt.setInt(5, cliente.getCodigo());
stmt.executeUpdate();
stmt.close();
JOptionPane.showMessageDialog(null,"Cadastro alterado com sucesso!");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void excluir(Cliente cliente) {
try {
PreparedStatement stmt = con.prepareStatement("delete from contato where codigo=?");
stmt.setInt(1, cliente.getCodigo());
stmt.executeUpdate();
stmt.close();
JOptionPane.showMessageDialog(null,"Cadastro excluido com sucesso!");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public ResultSet Navegar() {
try {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
// executa um select
stmt.executeQuery("select * from contato");
ResultSet rs = stmt.getResultSet();
// itera no ResultSet
return rs;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void desconectar(){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Bom, os botões "first" e "last" funcionam que é uma beleza, agora o "previous" cai direto na exceção e o "next" me joga direto para o primeito registro.
Alguém consegue apontar o meu erro?
Abraço.