JDBC:如何从结果集中检索SQL COUNT函数的结果?

Sol*_*ace 0 java mysql sql jdbc

通常,当我们想要从表中存在的数据库中检索一个值时,我们调用ResultSet的相应方法并将它传递给我们想要检索的列名.

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

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

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

Lui*_*oza 8

为列命名:

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

您还可以传递列的索引编号(如果您不想修改查询),该编号基于1.检查ResultSet#getInt(int columnIndex):

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

除此之外,如果使用a PreparedStatement来执行查询会更好,它具有许多优点,Statement如下所述:Statement和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");
Run Code Online (Sandbox Code Playgroud)