Select Count Java

Asked

Viewed 810 times

0

I want to select with the Count function and bring all the records of a table, but when presenting the quantity in the textfield, it displays a different result. I’ll put the code in for you to analyze:

Error presented

inserir a descrição da imagem aqui

My code

public void TrazerValores(){

        try {
             String Tabela = "tb_produtos";
            String query = "SELECT COUNT(*) FROM "+ Tabela ;


            //PEGANDO CONTAGEM DE VISITANTES
            PreparedStatement Stmt = con.prepareStatement(query);

            ResultSet rs = Stmt.executeQuery();
            txtTotalProdutos.setText(rs.toString());



        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Erro em buscar a quantidade");
        }        
    }

2 answers

1

If the intention is to display the search result, it is not by transforming the Resultset string, and yes, get the column value from it:

public void TrazerValores(){

        try {
             String Tabela = "tb_produtos";
            String query = "SELECT COUNT(*) FROM "+ Tabela ;


            //PEGANDO CONTAGEM DE VISITANTES
            PreparedStatement Stmt = con.prepareStatement(query);

            ResultSet rs = Stmt.executeQuery();
            rs.next();
            txtTotalProdutos.setText(rs.getString(1));



        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Erro em buscar a quantidade");
        }        
    }

I used getString(1) taking into account that the result will be a string, but depending on the type of the column, you can change this. The 1 refers to the column’s input that the value will be recovered, by your query, apparently the return will be a single column.

Recommended reading: Processing SQL Statements with JDBC

-1

In case it would be:

txtTotalProdutos.setText(String.valueOf(rs.getInt(1)));

For the count returns a value of type integer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.