Categories
Java SQL

Pretty print database SQL schema in Java using JDBC

How to pretty print a database SQL schema (table names, columns names and types), in Java using JDBC.

Starting from a JDBC connection object to your database called conn:

java.sql.Connection conn;

simply do:

DatabaseMetaData md = conn.getMetaData();
List<String> tableNames = new ArrayList<>();
ResultSet rs = md.getTables(null, null, "%", new String[]{"TABLE"});
while (rs.next())
    tableNames.add(rs.getString("TABLE_NAME"));

for (String tableName : tableNames) {
    System.out.println(tableName);
    System.out.println("--------------------------------------------------------------------");

    rs = md.getColumns(null, null, tableName, null);
    while (rs.next()) {
        String colName = rs.getString("COLUMN_NAME");
        String colType = rs.getString("TYPE_NAME");
        System.out.println(colName + " : " + colType);
    }

    System.out.println();
}

The console output is the following:

client
--------------------------------------------------------------------
id : uuid
name : varchar

product
--------------------------------------------------------------------
id : uuid
name : varchar

subscription
--------------------------------------------------------------------
id : uuid
client_id : uuid
product_id : uuid
name : varchar

Full working Java demo

Here is a working demo in a main, that starts a PostgreSQL using Testcontainers, creates a table using the following schema tables.sql:

CREATE TABLE client (ID UUID PRIMARY KEY, name VARCHAR(50) NOT NULL);

CREATE TABLE product (ID UUID PRIMARY KEY, name VARCHAR(50) NOT NULL);

CREATE TABLE subscription (ID UUID PRIMARY KEY,
                           client_id UUID NOT NULL,
                           product_id UUID NOT NULL,
                           name VARCHAR(50) NOT NULL);

and finally pretty prints the database schema using the code from above:

That’s it for this tutorial, thank you for reading ! If you have a question, please leave a reply below, we reply within 24 hours.

Leave a Reply

Your email address will not be published. Required fields are marked *