How to access SQL count () query value in Java program

I want to get the value that I find using the COUNT SQL command. Usually I enter the column name that I want to get in the getInt () method getString (), what should I do in this case when there is no specific column name.

I used "AS" in the same way as for the table alias, I'm not sure if this will work, I would not have thought.

Statement stmt3 = con.createStatement(); ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count"); while(rs3.next()){ count = rs3.getInt("count"); } 
+41
java sql count jdbc
May 04 '10 at 7:53 a.m.
source share
5 answers

Use aliases:

 SELECT COUNT(*) AS total FROM .. 

and then

 rs3.getInt("total") 
+70
May 04 '10 at 7:54 a.m.
source share
β€” -

The answers of Bohzo and Brabster will work, but you can also just use:

 rs3.getInt(1); 

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

+39
May 04 '10 at 8:02 a.m.
source share

I would expect this request to work with your program:

"SELECT COUNT(*) AS count FROM "+lastTempTable+")"

(You need to add a column alias, not a table)

+4
May 4 '10 at 7:55 a.m.
source share

I did it like this (example):

 String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"r@r.com"'"; int count=0; try { ResultSet rs = DatabaseService.statementDataBase().executeQuery(query); while(rs.next()) count=rs.getInt(1); } catch (SQLException e) { e.printStackTrace(); } finally { //... } 
+2
12 may '13 at 9:11
source share
 Statement stmt3 = con.createStatement(); ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;"); count = rs3.getInt("count"); 
+1
Aug 20 '13 at
source share



All Articles