How to get row count using ResultSet in Java?

前端 未结 13 2101
[愿得一人]
[愿得一人] 2020-11-27 13:05

I\'m trying to create a simple method that receives a ResultSet as a parameter and returns an int that contains the row count of the ResultSet. Is this a valid way of doing

13条回答
  •  遥遥无期
    2020-11-27 13:21

    If you have table and storing the ID as primary and auto increment then this will work

    Example code to get the total row count http://www.java2s.com/Tutorial/Java/0340__Database/GettheNumberofRowsinaDatabaseTable.htm

    Below is code

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    
    public class Main {
      public static void main(String[] args) throws Exception {
        Connection conn = getConnection();
        Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    
        st.executeUpdate("create table survey (id int,name varchar(30));");
        st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
        st.executeUpdate("insert into survey (id,name ) values (2,null)");
        st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
        st = conn.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM survey");
    
        rs = st.executeQuery("SELECT COUNT(*) FROM survey");
        // get the number of rows from the result set
        rs.next();
        int rowCount = rs.getInt(1);
        System.out.println(rowCount);
    
        rs.close();
        st.close();
        conn.close();
    
      }
    
      private static Connection getConnection() throws Exception {
        Class.forName("org.hsqldb.jdbcDriver");
        String url = "jdbc:hsqldb:mem:data/tutorial";
    
        return DriverManager.getConnection(url, "sa", "");
      }
    }
    

提交回复
热议问题