Share on Google+Share on Google+

JDBC Select Count example

Advertisement
In this tutorial we will learn how work COUNT() in query with mysql JDBC driver.

JDBC Select Count example

In this tutorial  we will learn how work COUNT()  in query with mysql JDBC driver. This tutorial  COUNT(*)  returns a count of the number of rows retrieved, whether or not they contain NULL values. Table of user :

Mysql query  "SELECT COUNT(*) FROM user"  count  number of rows,  whether or not they contain  NULL values. So this query count number  of  rows 5. If  change the COUNT(*) to COUNT(user_name)  then count number of rows 4 that contain user_name  it  ignore the  user_name  (NULL) value . The code of  "SelectCount.java" is:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
  
public class SelectCount{
 // JDBC driver name and database URL
 static String driverName = "com.mysql.jdbc.Driver";
 static String url = "jdbc:mysql://localhost:3306/";

 // defined and set value in  dbName, userName and password variables
 static String dbName = "testjdbc";
 static String userName = "root";
 static String password = "";
	
 public static void main(String[] args){
	// create Connection con, and Statement stmt 
	Connection con=null;
	Statement stmt=null;
	try{
		Class.forName(driverName).newInstance();
		con = DriverManager.getConnection(url+dbName, userName, password);
		try{
			stmt = con.createStatement();
			String query = "SELECT COUNT(*) FROM user";
			ResultSet rs=stmt.executeQuery(query);			
			//Extact result from ResultSet rs
			while(rs.next()){
			    System.out.println("COUNT(*)="+rs.getInt("COUNT(*)"));				
			  }
			// close ResultSet rs
			rs.close();
		   } catch(SQLException s){						
				s.printStackTrace();
			 }
		// close Connection and Statement
		con.close();
		stmt.close();
		}catch (Exception e){
			e.printStackTrace();
		 }
  }
}

Program Output :

F:\jdbc>javac SelectCount.java

F:\jdbc>java SelectCount
COUNT(*)=5

F:\jdbc>

Download Code

Advertisements

Posted on: October 15, 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.