Programa Exemplo

Galera eu estou começando a estudar java agora e estou usando o Livro JAVA FUNDAMENTOS SWING E JDBC, alguém ai tem um projeto simples que acesse firebird e que possa me passar os fontes pode ser qualquer coisa agenda, um simples cadastro.

[code]
import java.sql.;
import javax.swing.
;
import java.awt.;
import java.awt.event.
;

class Exemplo1305 extends JFrame implements ActionListener
{
JLabel L1,L2,L3,L4,L5,L6,L7,L8;
JButton b1,b2,b3,b4,b5;
static JTextField tfCodigo,tfNome,tfGenero,tfProdut,tfDatcom,tfAnopro,tfTemdur;
JPanel p1 = new JPanel();
ResultSet rs;
Statement MeuState;

public static void main(String args[])
{
JFrame Janela = new Exemplo1305();
Janela.show();
WindowListener x = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
Janela.addWindowListener(x);
}

Exemplo1305()
{
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
L1 = new JLabel("Código ");
L2 = new JLabel(“Título”);
L3 = new JLabel(“Gênero”);
L4 = new JLabel(“Produtora”);
L5 = new JLabel("Data de Compra “);
L6 = new JLabel(“Ano de Produção”);
L7 = new JLabel(“Tempo de Duração”);
L8 = new JLabel(” “);
for (int i=0;i<60;i++)
L8.setText(L8.getText()+” ");
tfCodigo = new JTextField(10);
tfCodigo.addActionListener(this);
tfNome = new JTextField(35);
tfGenero = new JTextField(10);
tfProdut = new JTextField(15);
tfDatcom = new JTextField(8);
tfAnopro = new JTextField(5);
tfTemdur = new JTextField(5);
b1=new JButton(“Inserir”);
b2=new JButton(“Atualizar”);
b3=new JButton(“Excluir”);
b4=new JButton(“Localizar”);
b5=new JButton(“Novo”);
b1.setBackground(new Color(180,180,250));
b2.setBackground(new Color(180,180,250));
b3.setBackground(new Color(180,180,250));
b4.setBackground(new Color(180,180,250));
b5.setBackground(new Color(180,180,250));
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
p1.add(L1); p1.add(tfCodigo); p1.add(L2); p1.add(tfNome);
p1.add(L3); p1.add(tfGenero); p1.add(L4); p1.add(tfProdut);
p1.add(L5); p1.add(tfDatcom); p1.add(L6); p1.add(tfAnopro);
p1.add(L7); p1.add(tfTemdur); p1.add(L8);
p1.add(b1); p1.add(b2); p1.add(b3);p1.add(b4);p1.add(b5);
getContentPane().add(p1);
setTitle(“Cadastramento de Filmes”);
setSize(600,140);
setResizable(false);
String url = “jdbc:odbc:MeuBanco”;
try
{
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” );
Connection MinhaConexao = DriverManager.getConnection(url);
MeuState = MinhaConexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = MeuState.executeQuery(“SELECT * FROM Filmes”);
rs.first();
atualizaCampos();
}
catch(ClassNotFoundException ex)
{
System.out.println(“Driver JDBC-ODBC não encontrado!”);
}
catch(SQLException ex)
{
System.out.println(“Problemas na conexao com a fonte de dados”);
}
}

public void actionPerformed(ActionEvent e)
{
if (e.getSource()==b5)
{
limpaCampos();
return;
}
if (e.getSource()==b1)
//inserir
{
try
{
String SQL = “INSERT INTO Filmes (Ficodigo,Finome,Figenero,” +
“Fiprodut,Fidatcom,Fianopro,Fitemdur) Values (’”+
tfCodigo.getText()+"’,’"+
tfNome.getText()+"’,’"+
tfGenero.getText()+"’,’"+
tfProdut.getText()+"’,’"+
tfDatcom.getText()+"’,’"+
tfAnopro.getText()+"’,’"+
tfTemdur.getText()+"’)";
MeuState.executeUpdate(SQL);
JOptionPane.showMessageDialog(null,“Gravação realizada com sucesso!”);
limpaCampos();
}
catch(SQLException ex)
{
if (ex.getMessage().equals(“General error”))
JOptionPane.showMessageDialog(null,“Filme já Cadastrado”);
else
JOptionPane.showMessageDialog(null,“Data Inválida”);
}

  } 

// ------------------ Final da Inclusão -------------------

if (e.getSource()==b2)
   //Atualizar
  {
  try
   {
   	String SQL = "UPDATE Filmes SET "+ 
   	  "Ficodigo='"+tfCodigo.getText()+"',"+
   	  "Finome='"+tfNome.getText()+"',"+
   	  "Figenero='"+tfGenero.getText()+"',"+
   	  "Fiprodut='"+tfProdut.getText()+"',"+
   	  "Fidatcom='"+tfDatcom.getText()+"',"+
   	  "Fianopro='"+tfAnopro.getText()+"',"+
   	  "Fitemdur='"+tfTemdur.getText()+"' "+
   	  "WHERE Ficodigo = '"+tfCodigo.getText()+"'";
   	  int r = MeuState.executeUpdate(SQL);
   	  if (r==1)
      	JOptionPane.showMessageDialog(null,"Atualização realizada com sucesso");
      else
        JOptionPane.showMessageDialog(null,"Esse Filme ainda não está cadastrado

Pressione Inserir");
}
catch(SQLException ex) { }
}
// ------------------ Final da Atualização -------------------
if (e.getSource()==b3)
// Excluir
{
try
{
String SQL = “SELECT Ficodigo, Finome FROM Filmes Where Ficodigo = '”+tfCodigo.getText()+"’";
rs = MeuState.executeQuery(SQL);
String nome = “”;
try
{
rs.next();
nome = “Deletar o Filme: “+rs.getString(“finome”);
}
catch(SQLException ex1)
{
JOptionPane.showMessageDialog(null,“Filme nao cadastrado!”);
return;
}
int n = JOptionPane.showConfirmDialog(null,nome,” “,JOptionPane.YES_NO_OPTION);
if (n==JOptionPane.YES_OPTION)
{
SQL = “DELETE FROM Filmes Where Ficodigo = '”+tfCodigo.getText()+”’”;
int r = MeuState.executeUpdate(SQL);
if (r==1)
JOptionPane.showMessageDialog(null,“Exclusão realizada com sucesso”);
else
JOptionPane.showMessageDialog(null,“Não foi possível excluir o filme”);
}
else
return;
}
catch(SQLException ex){ }
limpaCampos();
}
// ------------------ Final da Exclusão -------------------

if (e.getSource()==b4 || e.getSource()==tfCodigo)
{
try
{
String SQL = “SELECT * FROM Filmes Where Ficodigo = '”+tfCodigo.getText()+"’";
rs = MeuState.executeQuery(SQL);
rs.next();
tfCodigo.setText(rs.getString(“Ficodigo”));
tfNome.setText(rs.getString(“Finome”));
tfGenero.setText(rs.getString(“Figenero”));
tfProdut.setText(rs.getString(“Fiprodut”));
tfDatcom.setText(""+rs.getDate(“Fidatcom”));
tfAnopro.setText(rs.getString(“Fianopro”));
tfTemdur.setText(rs.getString(“Fitemdur”));
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog(null,“Filme nao Encontrado!”);
return;
}
}
// ------------------ Final da Localização -------------------
}

public static void limpaCampos()
{
tfCodigo.setText("");
tfNome.setText("");
tfGenero.setText("");
tfProdut.setText("");
tfDatcom.setText("");
tfAnopro.setText("");
tfTemdur.setText("");
}

public void atualizaCampos()
{
try
{
tfCodigo.setText(rs.getString(“Ficodigo”));
tfNome.setText(rs.getString(“Finome”));
tfGenero.setText(rs.getString(“Figenero”));
tfProdut.setText(rs.getString(“Fiprodut”));
tfDatcom.setText(""+rs.getDate(“Fidatcom”));
tfAnopro.setText(rs.getString(“Fianopro”));
tfTemdur.setText(rs.getString(“Fitemdur”));
}
catch(SQLException ex)
{ }
}
}[/code]

Simplesmente nota 10000000000000000000000000000000 esse exemplo… pra kem ta começando isso é uma mão na roda em tanto… O bom é não simplesmente se aproveitar e fazer o velho copy and paste… mas sim entender todo o fluxo do codigo em si, para que possamos realmente saber o que estamos a fazer.

Show de bola esse exemplo, Abdon! So precisa corrigir três coisas pra ficar legal de vez:

:arrow: Ao inves de usar Statements, e concatenar a String com a query e os parâmetros, é sempre, sempre melhor usar PreparedStatements.

:arrow: Nunca ignore uma SQLException! Se acontecer algum problema no acesso aos dados, vc nao fica nem sabendo do que aconteceu :frowning: - deixe pelo menos um e.printStackTrace(), ou monte um tratador de exceções único pra aplicação como um todo.

:arrow: Use a convenção de nomes da linguagem: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

Ola cv, Obrigado pelo elogio cara!
O PreparedStatements eu não sei usar :frowning: eu preciso aprender…
Mas eu já ouvi falar sobre ele, se eu não me engano ele serve para vc não errar nas querys e para elas funcionarem em qualquer banco, é isso msm?

Só aprender :smiley:

http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html