Search code examples
javamysqldatabaseresultseth2

Find all tables in a database with Java


I'm trying to get all the table names in my database back through Java but I am having problems using the Result Set. The below works and I can see the info listed when I inspect the result set. How do i get the table names from the result set into a collection?.

ResultSet rs;
rs = stat.executeQuery("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES");

Solution

  • You need to iterate over the ResultSet object in a loop:

    ResultSet rs;
    rs = stat.executeQuery("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES");
    
    List ll = new LinkedList();
    
    // Fetch each row from the result set
    while (rs.next()) {
      String tableName = rs.getString("TABLE_NAME");
    
      ll.add(tableName);
    }