[ *Início da Edição* ]
[color=red] Veja o 5° post...[/color]
[ *Fim da Edição* ]
E ae galera, gostaria de saber como utiliza o PreparedStatement.
Eu já fiz uns testes iniciais:
import java.sql.*;
class InseriTabelaComPS
{
public static void main (String args[])
{
try
{
String url = "jdbc:odbc:dataTesteJr";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
String x = "INSERT INTO tb_teste (cd_teste, nm_teste) VALUES (?,?)";
//Criando o P.S. e atribuindo a linha SQL "x" com interrogação
//no lugar dos valores
PreparedStatement PS = null;
PS = con.prepareStatement(x);
//Atribuindo valores aos "?" da String X
PS.setInt(1,50);
PS.setString(2,"Guitarra Flying V");
//Executando a atualização no BD do PS
PS.executeUpdate();
con.close();
}
catch(Exception e)
{
System.out.println("Erro: " + e.getMessage());
}
}
}
Mas o que estou tentando fazer agora com o PreparedStatement é exibir o resultado de uma pesquisa feita em um banco de dados. Esse banco possui 2 tabelas: tbcargos e tbfuncs.
Sou iniciante, fiz a parte gráfica, deu um trabalho, mas consegui:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
public class treinoPS extends Frame implements WindowListener
{
public static void main(String[] args)
{
treinoPS f = new treinoPS();
f.addWindowListener(f);
//Defindo propriedades do form
f.setTitle("Exemplo com labels");
f.setSize(350,210);
f.setLocation(320,200);
f.setLayout(new BorderLayout());
f.setBackground(Color.gray);
f.setResizable(false);
UIManager.put("Label.font", new Font("SansSerif", Font.BOLD, 12));
//UIManager.put("TextField.font", new Font("SansSerif", Font.BOLD, 12));
//Criando painel superior e seus componentes
Panel ps = new Panel();
JLabel lbNomePesquisa = new JLabel("Nome:");
TextField tfNomePesquisa = new TextField("Digite um nome e clique em pesquisar",30);
//--Definindo cor e localização dos componentes
ps.setBackground(Color.lightGray);
ps.add(lbNomePesquisa);
ps.add(tfNomePesquisa);
//Criando painel central e botão de pesquisar
Panel pc = new Panel();
Button btPesquisar = new Button("Pesquisar");
//--Adiconando botão pesquisar e definindo cor
pc.add(btPesquisar);
pc.setBackground(Color.lightGray);
//Criando painel inferior e seus respectivos componentes
Panel pi = new Panel();
JLabel lbNome = new JLabel("Nome:");
JLabel lbSalario = new JLabel("Salário:");
JLabel lbCargo = new JLabel("Cargo:");
TextField tfNome = new TextField("Nome");
TextField tfCargo = new TextField("Cargo");
TextField tfSalario = new TextField("Salário");
Button btAnterior = new Button("Anterior");
Button btProximo = new Button("Próximo");
//--Defindo gerenciador de layout, adicionando componentes, etc...
pi.setLayout(new GridLayout(4,2));
pi.setBackground(Color.lightGray);
pi.add(lbNome); pi.add(tfNome);
pi.add(lbSalario); pi.add(tfSalario);
pi.add(lbCargo); pi.add(tfCargo);
pi.add(btAnterior); pi.add(btProximo);
//Adicionando ao form
f.add(ps,BorderLayout.NORTH);
f.add(pc,BorderLayout.CENTER);
f.add(pi,BorderLayout.SOUTH);
//Exibindo
f.setVisible(true);
}
//Método para finalizar aplicação
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
}
Usando um bd feito no access mesmo, tenho que criar uma conexão com o ODBC. Já crescentei uns dados nas duas tabelas (cargos e funcionários (relacionamento de 1 p/ muitos)). Até aqui td bem.
O problema: ao clicar no botão pesquisar, deverá ser efetuado o SELECT utilizando LIKE para preencher um recordset e PreparedStatement para fazer o SQL. Os botões Próximo e Anterior devem permitir a navegação pelo recordset.
Quem souber como se faz me da uma força ae, enquanto isso vou continuar pesquisando, falou. :wink: