Select count Java

0

I want to make a select with the count function and bring all the records of a table, but when displaying the amount in the textfield, it displays a different result. I'll put the code for you to analyze:

Error Displayed

Mycode

publicvoidTrazerValores(){try{StringTabela="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");
        }        
    }
    
asked by anonymous 15.04.2017 / 03:46

1 answer

1

If the intention is to display the result of the search, it is not by transforming the Resultset into a string, but obtaining the column value:

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 that. The 1 refers to the index of the column that the value will be retrieved, by its query, apparently the return will be a single column.

Recommended reading: Processing SQL Statements with JDBC

    
15.04.2017 / 03:50