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.

 1Connection conn;
 2DatabaseMetaData dmd;
 3ResultSet rs1, rs2;
 4ResultSetMetaData rsmd;
 5Statement s;
 6try {
 7    conn = getConnection();
 8    dmd = conn.getMetaData();
 9    rs1 = dmd.getTables("database_name", null, "%", null);
10    s = conn.createStatement();
11    while (rs1.next()) {
12        System.out.println("# Processing table: " + rs1.getString(3));
13        rs2 = s.executeQuery("select * from " + rs1.getString(3));
14        rsmd = rs2.getMetaData();
15        for (int i = 0; i < rsmd.getColumnCount(); i++) {
16            System.out.print(rs2.getString(i + 1) + " ");
17        }
18        System.out.println();
19        rs2.close();
20    }
21}
22catch (SQLException sqle) {
23    sqle.printStackTrace();
24}
25finally {
26    conn.close();
27}