Reputation: 4949
How to get the outcome of the query-- the AVG(DIST).
MySQL is showing this result under the column "AVG(DIST)"-- no other clue.
How do i read this value from the ResultSet
instance (rs
in below code)?
PreparedStatement ps = c.prepareStatement("SELECT AVG(DIST) FROM POOL_TABLE");
ResultSet rs = ps.executeQuery();
ResultSet
seems to be referring to them all by column names.
Not well-familiar to JDBC -- yet!
TIA.
Upvotes: 1
Views: 414
Reputation: 1810
Here it is:
double avg = 0;
while (rs.next()) {
avg = rs.getDouble(1);
}
Use alias if you have many aggregate functions in your query. See below answer!
Upvotes: 2
Reputation: 347
PreparedStatement used for inserting of data, i think you should use Statement.
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT AVG(DIST) FROM POOL_TABLE");
if( rs.next() ){
System.out.print( rs.getString(1) );
}
i hope this example would help you :)
Upvotes: 0
Reputation: 9904
You can use an alias name in the query and retrieve the value in any of the two ways.!
PreparedStatement ps = c.prepareStatement("SELECT AVG(DIST) AS AVERAGE_ALIAS FROM POOL_TABLE");
ResultSet rs = ps.executeQuery();
double avg = 0;
while (rs.next()) {
avg = rs.getDouble(1);
// OR
avg= rs.getDouble("AVERAGE_ALIAS");
}
Upvotes: 6