2014-04-29 112 views
0

正常情况下,当我们想从表中存在的数据库中检索值时,我们调用ResultSet的适当方法并将它传递给我们想要检索的列名称。JDBC:如何从结果集中检索SQL COUNT函数的结果?

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

但是,当我们想在一个特定的列行(或字段)的计数(我们使用SQL COUNT函数),但我们如何检索结果。 我应该在下面这段代码中的rs.getInt()方法中传递什么参数?

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

检查这个答案http://stackoverflow.com/questions/192078/how-do-i-get-the-size-of-a-java-sql-resultset – gubble

+1

@在这种情况下,应用结果将得到1,而OP需要在数据库上执行“COUNT”函数。 –

+0

我的问题与此问题不同。他们想获得结果集的大小。我直接想要执行查询来获得行数! @gubble – Solace

回答

7

提供一个名称列:

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

您还可以通过列的索引的数量(如果你不想修改您的查询),这是1根据。检查ResultSet#getInt(int columnIndex)

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

除此之外,它会如果使用PreparedStatement来执行你的查询会更好,它具有许多优于普通Statement如下解释:Difference between Statement and PreparedStatement。你的代码是这样:

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(); 
int count = rs.getInt("count_name"); 
+0

非常感谢您的精心解答。我将尽快了解准备好的陈述。 – Solace

+0

@Zarah不客气。强烈建议您在使用普通JDBC而不是使用'Statement'接口时使用'PreparedStatement'。 –