[ajuda] erro no resultset

15 respostas
F

“Não localizou dadosorg.firebirdsql.jdbc.FBSQLException: The resultSet is not in a row, use next”

try

{

con_cidade.resultset.first();

tf_codigo.setText(con_cidade.resultset.getString(codigo));

tf_nome.setText(con_cidade.resultset.getString(nome));

}

catch(SQLException erro)

{

JOptionPane.showMessageDialog(null, Não localizou dados+erro);

}

}

/**

  • @param args the command line arguments
    */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new cadastros_cidades().setVisible(true);
    }
    });
    }
// Variables declaration - do not modify

private javax.swing.JButton btn_alterar;

private javax.swing.JButton btn_exluir;

private javax.swing.JButton btn_gravar;

private javax.swing.JButton btn_inserir;

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton2;

private javax.swing.JButton jButton3;

private javax.swing.JButton jButton4;

private javax.swing.JComboBox jComboBox1;

private javax.swing.JComboBox jComboBox2;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel5;

private javax.swing.JTextField tf_codigo;

private javax.swing.JTextField tf_nome;

private javax.swing.JTextField tf_pesquisa;

// End of variables declaration

}

onde está o problema? desde já muito obrigado.

15 Respostas

mgarcia

a exceçao pede para que ao inves de con_cidade.resultset.first() vc use con_cidade.resultset.next()

F

mas não adianta, o erro persiste =/

nel

Boa noite.

Antes de mais nada, quando postar código poste entre as tags corretas ok? Facilita muito a vida de quem pretende ajuda-lo! :slight_smile:
Leia este tópico, é importante: http://www.guj.com.br/posts/list/50115.java

Vamos ao seu código, amigo, seu código é assim mesmo ou deixou de postar algo? Não vejo onde você declara o ResultSet e nem como você faz para atribuir algum valor a variavél resultset. Está utilizando PreparedStatement? Efetuando corretamente a conexão com o banco?

Poste seu código completo, pelo menos desta sua classe, para que possamos ter uma melhor compreensão do seu código. E ai vai uma dica, antes de efetuar o resultset.getString(); como você fez, garanta que há algum registro no seu resultset, uma maneira óbvia e simples seria assim:

//se existir um registro, é true e entra no if
if(resultset.next()){
     resultset.getString("nome");
     //restante do seu código e dos getters.
}

Há! Ia esquecendo, caso queira pegar todos os registros podes usar da seguinte forma:

while(resultset.next()){ //sua lógica //os getters }

Espero ter ajudado!

Abraços!

F

bom, primeiramente eu gostaria de pedir desculpas por não ter postado com as tags corretamente. foi meu primeiro post no GUJ, e eu não tinha visto o tópico que explica como postar e tal. mas então, eu declarei e atribui valor à resultset na classe de conexão com o banco. ainda sou muito iniciante em java, e não entendi a questão de garantir um registro no resultset, como tu disse. mas, bom, essa é a classe completa do meu formulário:

package cadastros;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import utilitarios.conexao;
public class cadastros_cidades extends javax.swing.JFrame {
        int navega = 0;
        conexao con_cidade;
    
    public cadastros_cidades() {
        initComponents();
        
        con_cidade = new conexao();
        con_cidade.conecta();
        con_cidade.executeSQL("select * from cidade");
        
        try
        {
            con_cidade.resultset.first();
            tf_codigo.setText(con_cidade.resultset.getString("codigo"));
            tf_nome.setText(con_cidade.resultset.getString("nome"));
        }
        catch(SQLException erro)
        {
            JOptionPane.showMessageDialog(null, "Não localizou dados"+erro);
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tf_codigo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        tf_nome = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        btn_gravar = new javax.swing.JButton();
        btn_inserir = new javax.swing.JButton();
        btn_exluir = new javax.swing.JButton();
        btn_alterar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        tf_pesquisa = new javax.swing.JTextField();
        jComboBox2 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Manuten\u00e7\u00e3o do Cadastro de Cidades");
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel1.setForeground(new java.awt.Color(255, 0, 51));
        jLabel1.setText("Manuten\u00e7\u00e3o do Cadastro de Cidades");

        jLabel2.setText("C\u00f3digo.:");

        jLabel3.setText("Nome.:");

        jLabel4.setText("UF.:");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<selecione>", "RS", "SP", "SC", "RJ", "GO", "PR", "MG" }));

        jButton1.setText("<<");

        jButton2.setText("<");

        jButton3.setText(">");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText(">>");

        btn_gravar.setText("Gravar");
        btn_gravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_gravarActionPerformed(evt);
            }
        });

        btn_inserir.setText("Inserir");

        btn_exluir.setText("Exluir");

        btn_alterar.setText("Alterar");

        jLabel5.setText("Pesquisar.:");

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(78, 78, 78)
                .addComponent(btn_gravar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_inserir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_exluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_alterar)
                .addContainerGap(95, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(115, 115, 115)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton4)
                .addGap(130, 130, 130))
            .addGroup(layout.createSequentialGroup()
                .addGap(118, 118, 118)
                .addComponent(jLabel1)
                .addContainerGap(100, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5))
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tf_pesquisa, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                    .addComponent(tf_nome, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                    .addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(55, 55, 55)))
                .addGap(19, 19, 19)
                .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tf_pesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(tf_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton2)
                    .addComponent(jButton4)
                    .addComponent(jButton1))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_inserir)
                    .addComponent(btn_gravar)
                    .addComponent(btn_exluir)
                    .addComponent(btn_alterar))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>                        

    private void btn_gravarActionPerformed(java.awt.event.ActionEvent evt) {                                           
// TODO add your handling code here:
    }                                          

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try
        {
            con_cidade.resultset.next();
            tf_codigo.setText(con_cidade.resultset.getString("codigo"));
            tf_nome.setText(con_cidade.resultset.getString("nome"));
        }
        catch(SQLException erro)
        {
            System.out.println("Não localizou dados"+erro);
        }
    }                                        
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new cadastros_cidades().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton btn_alterar;
    private javax.swing.JButton btn_exluir;
    private javax.swing.JButton btn_gravar;
    private javax.swing.JButton btn_inserir;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField tf_codigo;
    private javax.swing.JTextField tf_nome;
    private javax.swing.JTextField tf_pesquisa;
    // End of variables declaration                   
    
}

e essa é a classe de conexão com o banco de dados:

package utilitarios;
import java.sql.*;
import javax.swing.*;

public class conexao
{
        final private String driver = "org.firebirdsql.jdbc.FBDriver";
        // voces verão ainda como efetuar conexão com diversos bancos
        final private String url = "jdbc:firebirdsql:localhost/3050:C:/Documents and Settings/Fabiel/Meus documentos/Java/Estoque/banco de dados/ESTOQUE.FDB";
        final private String usuario = "SYSDBA";
        final private String senha = "masterkey";
        private Connection conexao;
        public Statement statement;
        public ResultSet resultset;
        
       public boolean conecta()
       {
            boolean result = true;
            try 
            {
                Class.forName(driver);
                conexao = DriverManager.getConnection(url, usuario, senha);
                //JOptionPane.showMessageDialog(null,"conectou");
            }
            catch(ClassNotFoundException Driver) 
            {
               JOptionPane.showMessageDialog(null,"Driver não localizado: "+Driver);
               result = false;
            }
            catch(SQLException Fonte) 
            {
                JOptionPane.showMessageDialog(null,"Deu erro na conexão "+
                        "com a fonte de dados: "+Fonte);
                result = false;
            }
            return result; 
       }
       
       public void desconecta()
       {
            boolean result = true;
            try 
            {
                conexao.close();
                JOptionPane.showMessageDialog(null,"banco fechado");
            }
            catch(SQLException fecha) 
            {
                JOptionPane.showMessageDialog(null,"Não foi possivel "+
                        "fechar o banco de dados: "+fecha);
                result = false;
            }

       }
       
       public void executeSQL(String sql)
       {
            try 
            {
                statement = conexao.createStatement(
                ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
                resultset = statement.executeQuery(sql);
            }
            catch(SQLException sqlex) 
            {
               JOptionPane.showMessageDialog(null,"Não foi possível "+
                       "executar o comando sql,"+sqlex+", o sql passado foi "+sql);
            }

       }
       
}

desde já, muito obrigado!

nel

Não tem problemas, meu primeiro post também foi errôneo. Então, agora que eu vi o seu select.

Retire o ‘’ do seu select e faça com que retorne os campos que deseja, como '’ significa que você quer todas as colunas de uma determinada tabela precisa especificar qual(is) tabelas deseja que o select retorne com seus respectivos valores, ok?

Exemplo:

Select c.nome, c.estado From cidade c ok?

Sobre o resultset, quando você utiliza resultset.next() você está dizendo que é para ele pegar o próximo registro da tabela, mas supondo que ele não encontre ninguém na tabela, como você vai utilizar um resulset.get() concorda?

É só uma forma de garantir que retorne algum registro sem erros.
Não esqueça de modificar seu select e caso isso resolva seu problema poste [RESOLVIDO] ao lado do seu poste.

Abraços!! :slight_smile:

F

oi! bom… ainda não consegui.

mudei o select e ficou assim:

con_cidade.executeSQL("Select tf_pesquisa, jComboBox2, tf_codigo, tf_nome, jComboBox1, jButton1, jButton2, jButton3, jButton4, btn_gravar, btn_inserir, btn_exluir, btn_alterar From cidade");

ou seja, eu substitui o * por todos os componentes do formulário, incluindo botões. antes de incluir os botões, eu coloquei só os campos, mas ainda assim deu erro. agora o erro é diferente do erro de antes…

o que eu fiz de errado dessa vez?

abraço

nel

Bom dia.

Amigo, esse é um Select da linguagem SQL. Não se faz isso, buscar informações em componentes, jbuttos e etc…No máximo, pelo o que eu sei, é efetuar busca em um objeto entity utilizando JPA, mas o formato do select é o mesmo do SQL.

Você deve construir sua string select, insert e por ai vai…como se estivesse efetuando a busca diretamente no banco. Você fez Anterirormente:

Select * from cidade

Certo? Eu disse para mudar e buscar os campos que deseja, aqui vai uma suposição. Supondo que sua tabela cidade esteja assim:

Tabela cidade:

cidadeUID Integer Not Null; //chave primária nome VARCHAR(30); estado VARCHAR(30); totalPopulacao Integer Not Null;

Agora, em um select comum, você faria usando ‘*’ certo? Agora vamos fazer como deve usar no seu código:

con_cidade.executeSQL("Select c.cidadeUID, c.nome, c.estado, c.totalPopulacao from cidade c")

Entendido? Se resolver poste [RESOLVIDO] ao lado do seu tópico, caso volte a acontecer erros, poste o erro aqui ok? Apenas nos informando que um erro ocorrou será complicado de ajuda-lo.

Abraço! :slight_smile:

F

hum, entendi…

ficou assim con_cidade.executeSQL("Select nome, codigo from cidade c")

o erro do select parece que foi corrigido, mas agora voltou ao erro de antes, do resultset…

ps: em “codigo from cidade c”, pq esse “c” é necessário?

abraço!

F

up! ajudem aí :frowning:

nel

Boa tarde.

Na verdade, o ‘c’ no select foi um “apelido” dado a tabela cidade, no meu ponto de vista, isso facilita e garante o acesso correto a coluna que deseja da tabela em questão.

Sobre o resulset, qual erro está retornando no momento?

Altere o resultset.first() para resultset.next();

Também altere estas linhas: statement = conexao.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY); resultset = statement.executeQuery(sql);

para: statement = conexao.createStatement(sql); resultset = statement.executeQuery();

Abraços.

F

o erro que dá no resultset é “Não localizou dadosorg.firebirdsql.jdbc.FBSQLException: The resultSet is not in a row, use next”

alterei as linhas que tu disse, e o erro continua =/

abraço

nel

Opa.

Poste novamente seu código completo com as novas alterações, a Exception e linha que ela ocorre.
Abraços.

P.s: debuga seu código, vai facilitar muito.

F
package cadastros;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import utilitarios.conexao;
public class cadastros_cidades extends javax.swing.JFrame {
        int navega = 0;
        conexao con_cidade;
    
    public cadastros_cidades() {
        initComponents();
        
        con_cidade = new conexao();
        con_cidade.conecta();
        con_cidade.executeSQL("Select nome, codigo from cidade");
        
        try
        {
            con_cidade.resultset.next();
            tf_codigo.setText(con_cidade.resultset.getString("codigo"));
            tf_nome.setText(con_cidade.resultset.getString("nome"));
        }
        catch(SQLException erro)
        {
            JOptionPane.showMessageDialog(null, "Não localizou dados"+erro);
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tf_codigo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        tf_nome = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        btn_gravar = new javax.swing.JButton();
        btn_inserir = new javax.swing.JButton();
        btn_exluir = new javax.swing.JButton();
        btn_alterar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        tf_pesquisa = new javax.swing.JTextField();
        jComboBox2 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Manuten\u00e7\u00e3o do Cadastro de Cidades");
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel1.setForeground(new java.awt.Color(255, 0, 51));
        jLabel1.setText("Manuten\u00e7\u00e3o do Cadastro de Cidades");

        jLabel2.setText("C\u00f3digo.:");

        jLabel3.setText("Nome.:");

        jLabel4.setText("UF.:");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<selecione>", "RS", "SP", "SC", "RJ", "GO", "PR", "MG" }));

        jButton1.setText("<<");

        jButton2.setText("<");

        jButton3.setText(">");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText(">>");

        btn_gravar.setText("Gravar");
        btn_gravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_gravarActionPerformed(evt);
            }
        });

        btn_inserir.setText("Inserir");

        btn_exluir.setText("Exluir");

        btn_alterar.setText("Alterar");

        jLabel5.setText("Pesquisar.:");

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(78, 78, 78)
                .addComponent(btn_gravar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_inserir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_exluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_alterar)
                .addContainerGap(95, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(115, 115, 115)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton4)
                .addGap(130, 130, 130))
            .addGroup(layout.createSequentialGroup()
                .addGap(118, 118, 118)
                .addComponent(jLabel1)
                .addContainerGap(100, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5))
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tf_pesquisa, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                    .addComponent(tf_nome, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                    .addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(55, 55, 55)))
                .addGap(19, 19, 19)
                .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tf_pesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(tf_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton2)
                    .addComponent(jButton4)
                    .addComponent(jButton1))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_inserir)
                    .addComponent(btn_gravar)
                    .addComponent(btn_exluir)
                    .addComponent(btn_alterar))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>                        

    private void btn_gravarActionPerformed(java.awt.event.ActionEvent evt) {                                           
// TODO add your handling code here:
    }                                          

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try
        {
            con_cidade.resultset.next();
            tf_codigo.setText(con_cidade.resultset.getString("codigo"));
            tf_nome.setText(con_cidade.resultset.getString("nome"));
        }
        catch(SQLException erro)
        {
            System.out.println("Não localizou dados"+erro);
        }
    }                                        
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new cadastros_cidades().setVisible(true);
            }
        });
    }
package utilitarios;
import java.sql.*;
import javax.swing.*;

public class conexao
{
        final private String driver = "org.firebirdsql.jdbc.FBDriver";
        // voces verão ainda como efetuar conexão com diversos bancos
        final private String url = "jdbc:firebirdsql:localhost/3050:C:/Documents and Settings/Fabiel/Meus documentos/Java/Estoque/banco de dados/ESTOQUE.FDB";
        final private String usuario = "SYSDBA";
        final private String senha = "masterkey";
        private Connection conexao;
        public Statement statement;
        public ResultSet resultset;
        
       public boolean conecta()
       {
            boolean result = true;
            try 
            {
                Class.forName(driver);
                conexao = DriverManager.getConnection(url, usuario, senha);
                //JOptionPane.showMessageDialog(null,"conectou");
            }
            catch(ClassNotFoundException Driver) 
            {
               JOptionPane.showMessageDialog(null,"Driver não localizado: "+Driver);
               result = false;
            }
            catch(SQLException Fonte) 
            {
                JOptionPane.showMessageDialog(null,"Deu erro na conexão "+
                        "com a fonte de dados: "+Fonte);
                result = false;
            }
            return result; 
       }
       
       public void desconecta()
       {
            boolean result = true;
            try 
            {
                conexao.close();
                JOptionPane.showMessageDialog(null,"banco fechado");
            }
            catch(SQLException fecha) 
            {
                JOptionPane.showMessageDialog(null,"Não foi possivel "+
                        "fechar o banco de dados: "+fecha);
                result = false;
            }

       }
       
       public void executeSQL(String sql)
       {
            try 
            {
                statement = conexao.createStatement(
                  ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);  
                  resultset = statement.executeQuery(sql);  
            }
            catch(SQLException sqlex) 
            {
               JOptionPane.showMessageDialog(null,"Não foi possível "+
                       "executar o comando sql,"+sqlex+", o sql passado foi "+sql);
            }

       }
       
}
nel
public void executeSQL(String sql)  
        {  
             try   
             {  
                 statement = conexao.createStatement(  
                   ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);    
                   resultset = statement.executeQuery(sql);    
             }  
             catch(SQLException sqlex)   
             {  
                JOptionPane.showMessageDialog(null,"Não foi possível "+  
                        "executar o comando sql,"+sqlex+", o sql passado foi "+sql);  
             }  
   
        }

Você não alterou isso brother, altere para:

public void executeSQL(String sql)  
        {  
             try   
             {  
                 statement = conexao.createPreparedStatement(sql);    
                 resultset = statement.executeQuery();    
             }  
             catch(SQLException sqlex)   
             {  
                JOptionPane.showMessageDialog(null,"Não foi possível "+  
                        "executar o comando sql,"+sqlex+", o sql passado foi "+sql);  
             }  
   
        }

Altere também:

public Statement statement; PARA
public PreparedStatement statement;

Caso não resolva, poste o stacktrace completo do erro.
Abraços :)

F

alterei essas duas coisas, e agora o erro é esse:

init: deps-jar: Compiling 1 source file to C:\Documents and Settings\Fabiel\Meus documentos\Java\Estoque\build\classes C:\Documents and Settings\Fabiel\Meus documentos\Java\Estoque\src\utilitarios\conexao.java:61: cannot find symbol symbol : method createPreparedStatement(java.lang.String) location: interface java.sql.Connection statement = conexao.createPreparedStatement(sql); 1 error BUILD FAILED (total time: 0 seconds)

Criado 24 de outubro de 2009
Ultima resposta 2 de nov. de 2009
Respostas 15
Participantes 3