How do you access the value of an SQL count () query in a Java program

前端 未结 7 1140
梦毁少年i
梦毁少年i 2021-02-01 00:54

I want to get to the value I am finding using the COUNT command of SQL. Normally I enter the column name I want to access into the getInt() getString() method, what do I do in t

相关标签:
7条回答
  • 2021-02-01 00:56
    Statement stmt3 = con.createStatement();
    
    ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
    
    count = rs3.getInt("count");
    
    0 讨论(0)
  • 2021-02-01 00:57

    The answers provided by Bohzo and Brabster will obviously work, but you could also just use:

    rs3.getInt(1);
    

    to get the value in the first, and in your case, only column.

    0 讨论(0)
  • 2021-02-01 00:58

    I have done it this way (example):

    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 {
        //...
    }
    
    0 讨论(0)
  • 2021-02-01 01:01
            <%
            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);  
            }
    
            %>
    
    0 讨论(0)
  • 2021-02-01 01:09

    Use aliases:

    SELECT COUNT(*) AS total FROM ..
    

    and then

    rs3.getInt("total")
    
    0 讨论(0)
  • 2021-02-01 01:09

    It's similar to above but you can try like

    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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题