简体   繁体   中英

JDBC — ResultSet values for column functions

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.

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");
}

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!

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM