import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TableList
{
  public TableList(Connection dataConnection, String schema)
  {
    DatabaseMetaData databaseMetaData = null;
    ResultSet tableNames = null;
    String query;
    Statement statement = null;
    ResultSet rowCount = null;
    int numberOfTables = 0;
    int numberOfRows =0;
    int i = 0;
    String[] tableName;
    String[] tableTypes = {"TABLE"};
    
    try
    {
      databaseMetaData = dataConnection.getMetaData();
    }
    catch (SQLException e)
    {
      e.printStackTrace();
    }
    
    try
    {
      tableNames = 
        databaseMetaData.getTables(null, "public", null, tableTypes);
    }
    catch (SQLException e)
    {
      e.printStackTrace();
    }
    
    tableName = new String[1024];
    try
    {
      i = 0;
      while (tableNames.next())
      {
        tableName[i] = new String(tableNames.getString("table_name"));
        i++;
      }
    }
    catch (SQLException e)
    {
      e.printStackTrace();
    }
    
    numberOfTables = i;
    System.out.println("Number of tables: " + numberOfTables);
    for (i = 0; i < numberOfTables; i++)
    {
      query = new String
          ("select count(*) as row_count from " + tableName[i] +';');
      try
      {
        statement = dataConnection.createStatement();
      }
      catch (SQLException e)
      {
        e.printStackTrace();
      }
      try
      {
        rowCount = statement.executeQuery(query);
      }
      catch (SQLException e)
      {
        e.printStackTrace();
      }
      try
      {
        if (rowCount.next())
        {
          numberOfRows = rowCount.getInt("row_count");
        }
      }
      catch (SQLException e)
      {
        e.printStackTrace();
      }
      System.out.println
      (
        "Table: " + 
        tableName[i] + 
        ", Row count: " + 
        numberOfRows
      );
    }
  }
}
