Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access the value of an SQL count () query in a Java program

Tags:

java

sql

count

jdbc

I want to get to the value I am finding using the COUNT command of SQL. Normally I enter the column name I want to access into the getInt() getString() method, what do I do in this case when there is no specific column name.

I have used 'AS' in the same manner as is used to alias a table, I am not sure if this is going to work, I would think not.

Statement stmt3 = con.createStatement(); ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count");     while(rs3.next()){     count = rs3.getInt("count");     } 
like image 307
Ankur Avatar asked May 04 '10 07:05

Ankur


People also ask

How do you run a count query in Java?

How to count rows – count (*) and 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.

What does count () mean in SQL?

The COUNT() function returns the number of rows that matches a specified criterion.

How do you count queries in SQL?

SELECT COUNT(*) FROM table_name; The COUNT(*) function will return the total number of items in that group including NULL values. The FROM clause in SQL specifies which table we want to list. You can also use the ALL keyword in the COUNT function.

How do you query in SQL Java?

STEP 1: Allocate a Connection object, for connecting to the database server. STEP 2: Allocate a Statement object, under the Connection created earlier, for holding a SQL command. STEP 3: Write a SQL query and execute the query, via the Statement and Connection created. STEP 4: Process the query result.


2 Answers

Use aliases:

SELECT COUNT(*) AS total FROM .. 

and then

rs3.getInt("total") 
like image 90
Bozho Avatar answered Sep 26 '22 00:09

Bozho


The answers provided by Bohzo and Brabster will obviously work, but you could also just use:

rs3.getInt(1); 

to get the value in the first, and in your case, only column.

like image 44
Eric Eijkelenboom Avatar answered Sep 23 '22 00:09

Eric Eijkelenboom