Student Student - 8 months ago 32
Java Question

Correct way to find rowcount in Java JDBC

I have tried different ways to get the row count in java JDBC, nut none seemed to be giving the correct result. Is there anything wrong that I am doing ?

Even though the customer table is empty and I should be getting the rowcount as 0, I don't understand why I get a non zero rowcount value.

Method 1 -

query = "SELECT * FROM customer WHERE username ='"+username+"'";
rs = stmt.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
rowcount = metaData.getColumnCount();

Method 2 -

query = "SELECT * FROM customer WHERE username ='"+username+"'";
rs = stmt.executeQuery(query);
rowcount = rs.last() ? rs.getRow() : 0;


See this snippet of code:

import java.sql.*;

public class CountRows{
  public static void main(String[] args) {
  System.out.println("Count number of rows in a specific table!");
  Connection con = null;
  int count = 0;
  con = DriverManager.getConnection
  Statement st = con.createStatement();
  BufferedReader bf = new BufferedReader(new InputStreamReader(;
  System.out.println("Enter table name:");
  String table = bf.readLine();
  ResultSet res = st.executeQuery("SELECT COUNT(*) FROM "+table);
  while ({
  count = res.getInt(1);
  System.out.println("Number of row:"+count);
  catch (SQLException s){
  System.out.println("SQL statement is not executed!");
  catch (Exception e){