SELECT count(*) FROM cadastro

8 respostas
A

Ola Pessoa estou querendo criar um contador dentro do mysql para poder contar os numeros de ID dos clientes exemplo estou criando um interface onde eu quero pegar um label e colocar o ultimo numero do Id do cliente que consta no banco de dados…

estou usando as seguintes expressoes

public ResultSet contador()
{

String sql;

sql = “SELECT count(*) FROM cadastro”;

try
    {
               	conexao = new Conexao();
    	Statement stm = conexao.getConexao).createStatement();
    	ResultSet teste=stm.executeQuery(sql);
    	return teste;
    } 
    catch (Exception e) 
    {
    	e.printStackTrace();
    
    }
	return null;
	
        

 }

no meu main criei a instancia bonitinha e coloquei assim pra retornar o valor System.out.println(p.contador)

So que me retorna isto com.mysql.jdbc.ResultSet@6e1408

Alguem pode me ajudar?

8 Respostas

I

public int contador()
{

String sql;

sql = “SELECT count(*) FROM cadastro”;

try

{

conexao = new Conexao();

Statement stm = conexao.getConexao).createStatement();

ResultSet teste=stm.executeQuery(sql);

return teste.getInt(count(*));

}

catch (Exception e)

{

e.printStackTrace();

}
return null;

Espero ter ajudado!

A

não deu certo ta dando o seguinte erro.

java.sql.SQLException: Before start of result set

at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:3624)

at com.mysql.jdbc.ResultSet.getString(ResultSet.java:1763)

at com.mysql.jdbc.ResultSet.getInt(ResultSet.java:1258)

at com.mysql.jdbc.ResultSet.getInt(ResultSet.java:1294)

at Stringes.StringesMYSQL.contador(StringesMYSQL.java:96)

at Interface.Cadastro$1.actionPerformed(Cadastro.java:136)

at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)

at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)

at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)

at javax.swing.DefaultButtonModel.setPressed(Unknown Source)

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)

at java.awt.Component.processMouseEvent(Unknown Source)

at javax.swing.JComponent.processMouseEvent(Unknown Source)

at java.awt.Component.processEvent(Unknown Source)

at java.awt.Container.processEvent(Unknown Source)

at java.awt.Component.dispatchEventImpl(Unknown Source)

at java.awt.Container.dispatchEventImpl(Unknown Source)

at java.awt.Component.dispatchEvent(Unknown Source)

at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)

at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)

at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)

at java.awt.Container.dispatchEventImpl(Unknown Source)

at java.awt.Window.dispatchEventImpl(Unknown Source)

at java.awt.Component.dispatchEvent(Unknown Source)

at java.awt.EventQueue.dispatchEvent(Unknown Source)

at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)

at java.awt.EventDispatchThread.pumpEvents(Unknown Source)

at java.awt.EventDispatchThread.pumpEvents(Unknown Source)

at java.awt.EventDispatchThread.run(Unknown Source)

0
A

Descobri oq era…

Faltou o teste.next();

F

se vc quer apenas mostrar a ultima ID o teu select esta errado, pois quando forem apagados registros vai dar zebra. Basta fazer assim:

select max(id) from suaTabela
E

Creio que o erro esta em não colocar o “;” no final da string sql.
eu fiz assin "SELECT COUNT() FROM TAB_DOCS;"
e sai COUNT(
): 906

E
Ahh! Coste que minha tablela tem 906 registros e que o COUNT(*):  é o resultado de fazer:

String colName = rsmd.getColumnName(i);

jta.append (colName+": “+ rs.getString(colName)+”\n");

Espero ter colaborado. Em caso de dúvida me escreva.
F

tenho assim no mysql

mysql> select * from oprd_servico;

ERROR 1146 (42S02): Table ‘criabanco.oprd_servico’ doesn’t exist

mysql> select * from ord_servico;

±------------±-------------------±--------±--------------------±-----------

-±---------±----------------+

| cod_cliente | nome               | unidade | data                | cod_servico

| valor    | obs             |

±------------±-------------------±--------±--------------------±-----------

-±---------±----------------+

|           3 | NULL               |         | 2007-06-15 17:24:31 | 3

| 1.000,00 | ttttttttt       |

|           2 | NULL               | BBG7    | 2007-06-15 17:37:18 | 4

| 500,00   | teste           |

|           5 | NULL               |         | 2007-06-15 17:48:21 | 2

| 800,00   | TesteInstalacao |

| 10 | NULL | | 2007-06-22 00:00:00 | 3
| 1100,00 | teste dia 22 |
| 11 | NULL | CCD2 | 2007-06-22 00:00:00 | 4
| 1200,00 | testes dia 22 |
| 11 | NULL | FFD2 | 2007-06-22 00:00:00 | 4

e tenho esta classe

public class teste {

public static void main(String args[]) {
    /* Eu preciso no lugar do 06 receber uma variavel da classe listagens para retornar o mes que eu quero que apareça na listagens*/
    /* por exemplo String mesi ="x";*/
    String mesi = "06";
    String mesf = "06";        
               
    SimpleDateFormat sdg = new SimpleDateFormat("dd/MM/yyyy");        
    String dataFormatada = null;
    
    String x="3";
    //String SQL="select * from ord_servico where data between 2007-06-01 and 2007-06-31"; 
         
    //String SQL = "select * from ord_servico where cod_servico=3 and (data > '2007-"+mesi+"-01' and data < '2007-"+mesf+"-31') " ;
    
    try { 
        Connection con  = ConnectionFactory.getConnection();
        Statement stmt  = con.createStatement();
        ResultSet  rs   = stmt.executeQuery("select count(* ) from ord_servico where data > '2007-06-15 17:24:31' and data < '2007-07-15 17:24:31' and cod_servico = 4");

        //System.out.println(rs);
        while(rs.next()){
            String uni = rs.getString("cod_servico");
            try {
               dataFormatada = sdg.format(rs.getDate("data"));
           } catch (Exception ex) {
                 System.out.println("Erro formatando a data");
             } 
            
            
            //Date dat   = rs.getDate("data");
            String val = rs.getString("valor");
            String  ob = rs.getString("obs");
           
                          
            // pela query. Vamos imprimí-los   
             // System.out.println("unidade: " + uni+ "--> data: "+ dataFormatada +" --> valor: " + val + " --> obs: "+ ob);
              System.out.println("-->"+uni+"-->"+dataFormatada+"-->"+val+"-->"+ob);
              
              System.out.println(dataFormatada);
        }
        
       


    } catch (SQLException ex) {
    // handle any errors
    System.out.println("Outro:"+ex);
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());
    } catch (Exception ex) {
         System.out.println("Erro: "+ex);
         // handle the error
     }  
}

}
preciso que retorne no mes qtos registro com cod_servico =4 estao cadastrados o mysql tá retornando dizendo que nao existe esta coluna…poxa gente preciso de ajuda…

M

ResultSet rs = stmt.executeQuery(“select count(* ) from ord_servico where data > ‘2007-06-15 17:24:31’ and data < ‘2007-07-15 17:24:31’ and cod_servico = 4”);

<a href="//System.out.println">//System.out.println</a>(rs);

while(rs.next()){

String uni = rs.getString(cod_servico);  </blockquote>

Você esta selecionando o “count(*)” no SQL e tentando pegar o cod_serviço.
Se você quer pegar a quantidade de linhas retornadas, use “select count(1) …”, se você quiser as linhas, usa “select * …” (ou select campo1, campo2…)

Criado 21 de maio de 2006
Ultima resposta 28 de jun. de 2007
Respostas 8
Participantes 6