What is the return type of a “count” query against MySQL using Java JDBC?


The return type of count is long. The Java statement is as follows

rs.next();
long result= rs.getLong("anyAliasName");

First, create a table with some records in our sample database test3. The query to create a table is as follows

mysql> create table CountDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into CountDemo(Name) values('John');
Query OK, 1 row affected (0.21 sec)
mysql> insert into CountDemo(Name) values('Carol');
Query OK, 1 row affected (0.16 sec)
mysql> insert into CountDemo(Name) values('Bob');
Query OK, 1 row affected (0.19 sec)
mysql> insert into CountDemo(Name) values('David');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from CountDemo;

The following is the output

+----+-------+
| Id | Name  |
+----+-------+
| 1 | John   |
| 2 | Carol  |
| 3 | Bob    |
| 4 | David  |
+----+-------+
4 rows in set (0.00 sec)

Here is the Java code return type of a “count” query against MySQL using Java JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ReturnTypeOfCount {
   public static void main(String[] args) {
      Connection con=null;
      Statement st=null;
      ResultSet rs=null;
      try {
         con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test3?useSSL=false",
         "root","123456");
         String yourQuery = "SELECT COUNT(*) AS totalCount FROM CountDemo";
         st = con.createStatement();
         rs = st.executeQuery(yourQuery);
         rs.next();
         long result= rs.getLong("totalCount");
         System.out.println("Total Count="+result);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The following is the output

Total Count=4
Here is the snapshot of the output:

Updated on: 30-Jul-2019

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements