简体   繁体   中英

JDBC: How to retrieve the result of SQL COUNT function from the result set?

Normally when we want to retrieve a value from our database which is present in the table, we call the appropriate method of ResultSet and pass it the column name which we want to retrieve.

   ResultSet rs= stmt.executeQuery("select name from db.persons where school ='"+sch+"'");
    int count= rs.getString("person_name");

But when we want to get a count of rows (or fields) in a particular column (we use the SQL COUNT function) but how do we retrieve the result. What argument should I pass in the rs.getInt() method in the following piece of code?

ResultSet rs= stmt.executeQuery("select count(name) from db.persons where school ='"+sch+"'");
int count= rs.getInt( ????? );

Give a name to the column:

ResultSet rs= stmt.executeQuery("select count(name) AS count_name from db.persons where school ='"+sch+"'");
if (rs.next()) {
    int count= rs.getInt("count_name");
}

You could also pass the number of the index of the column (in case you don't want to modify your query) which is 1 based. Check ResultSet#getInt(int columnIndex) :

ResultSet rs= stmt.executeQuery("select count(name) from db.persons where school ='"+sch+"'");
if (rs.next()) {
    int count= rs.getInt(1);
}

Apart from this, it would be better if you use a PreparedStatement to execute your queries, it has many advantages over plain Statement as explained here: Difference between Statement and PreparedStatement . Your code would look like:

String sql = "select count(name) AS count_name from db.persons where school = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, sch);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
    int count = rs.getInt("count_name");
}

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