Share on Google+Share on Google+

Rows Count Example Using JDBC ResultSet

Advertisement
In this tutorial you can count the number of rows in the database table using ResultSet. Through this example, you can do it.

Rows Count Example Using  JDBC ResultSet:

In this tutorial you can count the number of rows in the database table using ResultSet. Through this example, you can do it.

First of all, we will create a java class CountRows.java class. In this class we will create database connection as:

Connection connection = null;

String url = "jdbc:mysql://localhost:3306/";

String dbName = "roseindia_jdbc_tutorials";

String driverName = "com.mysql.jdbc.Driver";

String userName = "root";

String password = "root";

Class.forName(driverName).newInstance();

connection = DriverManager.

getConnection(url+dbName, userName, password);

Now we will create a Statement object for execute SQL statements as:

Statement stmt = connection.createStatement();

Now we will create SQL select statement with count method and execute on created statement object and store result in the ResultSet as:

String selectquery = "select count(*) from user";

ResultSet rs = stmt.executeQuery(selectquery);

Now fetch the ResultSet object using next() and find the number of rows as:

rs.next();

System.out.println("Number of rows :" + rs.getInt(1));

The full code of the example is:

package ResultSet;
import java.sql.*;
public class CountRows {

  public static void main(String[] args) {
    Connection connection = null;
      String url = "jdbc:mysql://localhost:3306/";
      String dbName = "roseindia_jdbc_tutorials";
      String driverName = "com.mysql.jdbc.Driver";
      String userName = "root";
      String password = "root";
      try{
        Class.forName(driverName).newInstance();
        connection = DriverManager.getConnection(url+dbName, userName, password);
        try{
          Statement stmt = connection.createStatement();
          String selectquery = "select count(*) from user";
          ResultSet rs = stmt.executeQuery(selectquery);
          rs.next();          
          System.out.println("Number of rows :" + rs.getInt(1));
        }
        catch(SQLException s){
          System.out.println(s);
        }
        connection.close();
      }
      catch (Exception e){
        e.printStackTrace();
      }
  }
}

Now we will run this example using eclipse IDE and see the output:

Program output:

Database table is:

The eclipse console output is:

Download source code

Advertisements

Posted on: October 20, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.