avatar

Andres Jaimes

Read all tables and columns from a database using Java

By Andres Jaimes

This Java example finds all the tables and their corresponding columns from a database. The code iterates over the entities and columns found and shows them on the console.

Minor changes are necessary to process the found values in a different way.

Connection conn;
DatabaseMetaData dmd;
ResultSet rs1, rs2;
ResultSetMetaData rsmd;
Statement s;
try {
    conn = getConnection();
    dmd = conn.getMetaData();
    rs1 = dmd.getTables("database_name", null, "%", null);
    s = conn.createStatement();
    while (rs1.next()) {
        System.out.println("# Processing table: " + rs1.getString(3));
        rs2 = s.executeQuery("select * from " + rs1.getString(3));
        rsmd = rs2.getMetaData();
        for (int i = 0; i < rsmd.getColumnCount(); i++) {
            System.out.print(rs2.getString(i + 1) + " ");
        }
        System.out.println();
        rs2.close();
    }
}
catch (SQLException sqle) {
    sqle.printStackTrace();
}
finally {
    conn.close();
}