Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to find rowcount in Java JDBC

Tags:

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;
like image 415
Student Avatar asked Oct 27 '12 18:10

Student


People also ask

How do I count the number of rows in Java?

The SQL Count() function returns the number of rows in a table. Using this you can get the number of rows in a table.

How do you get RowCount?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.

How do I get RowCount in SQL?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

How do I find the number of rows in a ResultSet?

To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row.


1 Answers

See this snippet of code:

import java.io.*;
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;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial","root","root");
            try {
                Statement st = con.createStatement();
                BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("Enter table name:");
                String table = bf.readLine();
                ResultSet res = st.executeQuery("SELECT COUNT(*) FROM "+table);
                while (res.next()){
                    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){
            e.printStackTrace();
        }
    }
}
like image 183
Kumar Vivek Mitra Avatar answered Sep 28 '22 00:09

Kumar Vivek Mitra