如何在Java程序中访问SQL count()查询的值

时间:2010-05-04 07:53:34

标签: java sql jdbc count

我想使用SQL的COUNT命令获取我找到的值。通常我在getInt()getString()方法中输入我想要访问的列名,在没有特定列名的情况下我该怎么做。

我使用'AS'的方式与用于别名表的方式相同,我不确定这是否会起作用,我认为不会。

Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count");
    while(rs3.next()){
    count = rs3.getInt("count");
    }

7 个答案:

答案 0 :(得分:88)

使用别名:

SELECT COUNT(*) AS total FROM ..

然后

rs3.getInt("total")

答案 1 :(得分:43)

BohzoBrabster提供的答案显然有效,但您也可以使用:

rs3.getInt(1);

获取第一个值,在您的情况下只有列。

答案 2 :(得分:4)

我希望此查询适用于您的程序:

"SELECT COUNT(*) AS count FROM "+lastTempTable+")"

(您需要对列进行别名,而不是表格)

答案 3 :(得分:2)

我这样做了(例子):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"r@r.com"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

答案 4 :(得分:1)

Statement stmt3 = con.createStatement();

ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");

count = rs3.getInt("count");

答案 5 :(得分:1)

        <%
        try{
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
            if(con == null) System.out.print("not connected");
            Statement st = con.createStatement();
            String myStatement = "select count(*) as total from locations";
            ResultSet rs = st.executeQuery(myStatement);
            int num = 0;
            while(rs.next()){
                num = (rs.getInt(1));
            }

        }
        catch(Exception e){
            System.out.println(e);  
        }

        %>

答案 6 :(得分:0)

与上面类似,但是您可以尝试

public Integer count(String tableName) throws CrateException {
        String query = String.format("Select count(*) as size from %s", tableName);
        try (Statement s = connection.createStatement()) {
            try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
                Preconditions.checkArgument(resultSet.next(), "Result set is empty");
                return resultSet.getInt("size");
            }
        } catch (SQLException e) {
            throw new CrateException(e);
        }
    }
}