Kode Java – Learn Java by Examples

Learn Java by Examples

Learn Java by Examples

Java

Java

  • Java
    • Basic
    • Core API
    • 2D API
    • Lang Package
    • Util Package
    • Applet
    • AWT
    • Networking
    • Java Date Time API
    • Concurrency
    • Cryptography
    • IO
    • Logging
    • Zip and GZIP
    • Reflection
    • Regex
    • JDBC
    • Scripting
    • Stream API
    • Beans
    • Mail
    • Security
    • XML
    • Sound API
    • Swing
    • HttpClient
    • Java 8
    • Java 9
    • Java 10
    • Java 11
    • Java 12
    • Java 14
    • Java 15
    • Java 16
    • Java 17
    • Java 25
Spring

Spring

  • Spring
    • Spring Core
    • Spring JDBC
    • Spring Data JPA
    • Spring Boot
    • Spring MVC
    • Spring Security
Persistence

Persistence

  • Persistence
    • Java Persistence API
    • Hibernate
    • MyBatis
Servlet

Servlet

  • Servlet
    • Servlet
    • JSP
    • Taglib
Other Libraries

Other Libraries

  • Other Libraries
    • Apache Commons
    • Apache HttpComponents
    • Apache POI
    • E-iceblue Spire
    • Google Gson
    • iText PDF
    • Jackson
    • Jasypt
    • JDOM
    • Joda-Time
    • jPOS
    • JSch
    • JSON-Java
    • Project Lombok
    • ZK Framework
Patterns

Patterns

  • Patterns
    • Creational Patterns
Android

Android

  • Android
    • Android Misc
Databases

Databases

  • Databases
    • Learning SQL
    • MySQL
    • MongoDB
    • Microsoft Access
JVM Languages

JVM Languages

  • JVM Languages
    • Kotlin
Tools

Tools

  • Tools
    • IntelliJ IDEA
    • Gradle
    • Docker
    • JUnit
    • Maven
    • OS X
    • Ubuntu
    • PlantUML
    • UML
Partners

Partners

  • Partners
    • Buku Java ID

Tag Archives: DatabaseMetaData

How do I use DatabaseMetaData to inspect schema in JDBC?

By Wayan in JDBC Last modified: March 22, 2026 0 Comment

You use java.sql.DatabaseMetaData by:

  1. Opening a Connection
  2. Calling conn.getMetaData()
  3. Querying catalogs/schemas/tables/columns/keys/indexes via the DatabaseMetaData “getXxx” methods (they mostly return ResultSets)
  4. Reading those result sets like normal query results

Below are the most common inspection tasks and the JDBC calls that power them.


1) Get the DatabaseMetaData

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

public class DatabaseMetadata1 {
    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {

            DatabaseMetaData md = conn.getMetaData();

            System.out.println(md.getDatabaseProductName() + " " + md.getDatabaseProductVersion());
            System.out.println(md.getDriverName() + " " + md.getDriverVersion());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If you’re using a DataSource, it’s the same idea: try (Connection conn = dataSource.getConnection()) { ... }.


2) Understand the “filter” parameters (the #1 gotcha)

Many methods take filters like:

  • catalog (often the database name; sometimes unused)
  • schemaPattern (SQL pattern: % wildcard; sometimes case-sensitive depending on DB)
  • tableNamePattern (pattern)
  • types (e.g., {"TABLE","VIEW"})

Patterns are not regex; they’re SQL LIKE-style patterns:

  • % = any sequence
  • _ = any single character

Also: some databases store identifiers in upper-case/lower-case internally. Use:

  • md.storesUpperCaseIdentifiers()
  • md.storesLowerCaseIdentifiers()
  • md.supportsSchemasInTableDefinitions()

3) List catalogs and schemas

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class DatabaseMetadata2 {
    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {
            DatabaseMetaData md = conn.getMetaData();

            try (ResultSet rs = md.getCatalogs()) {
                while (rs.next()) {
                    System.out.println("Catalog: " + rs.getString("TABLE_CAT"));
                }
            }

            try (ResultSet rs = md.getSchemas()) {
                while (rs.next()) {
                    System.out.println("Schema: " + rs.getString("TABLE_SCHEM")
                                       + " (catalog=" + rs.getString("TABLE_CATALOG") + ")");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Column names like "TABLE_SCHEM" are specified by the JDBC spec for each metadata result set. (They feel a bit “old-school”, but they’re standard.)


4) List tables (and views)

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class DatabaseMetadata3 {
    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {
            DatabaseMetaData md = conn.getMetaData();

            String catalog = null;            // or your catalog name
            String schemaPattern = "public";  // adjust for your DB; or "%"
            String tablePattern = "%";
            String[] types = {"TABLE", "VIEW"};

            try (ResultSet rs = md.getTables(catalog, schemaPattern, tablePattern, types)) {
                while (rs.next()) {
                    String schema = rs.getString("TABLE_SCHEM");
                    String table  = rs.getString("TABLE_NAME");
                    String type   = rs.getString("TABLE_TYPE");
                    System.out.println(type + " " + schema + "." + table);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5) Inspect columns for a table

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class DatabaseMetadata4 {
    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {
            DatabaseMetaData md = conn.getMetaData();

            String catalog = null;
            String schema = "public";
            String table = "users";

            try (ResultSet rs = md.getColumns(catalog, schema, table, "%")) {
                while (rs.next()) {
                    String col = rs.getString("COLUMN_NAME");
                    int jdbcType = rs.getInt("DATA_TYPE");          // java.sql.Types
                    String dbType = rs.getString("TYPE_NAME");      // vendor type name
                    int size = rs.getInt("COLUMN_SIZE");
                    int nullable = rs.getInt("NULLABLE");           // DatabaseMetaData.columnNullable/NoNulls
                    String def = rs.getString("COLUMN_DEF");

                    System.out.printf("%s %s(%d) nullable=%s default=%s%n",
                            col, dbType, size,
                            (nullable == DatabaseMetaData.columnNullable),
                            def);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If you need precision/scale for numeric columns, also read:

  • DECIMAL_DIGITS
  • NUM_PREC_RADIX

6) Primary keys, foreign keys, and indexes

Primary key

try (ResultSet rs = md.getPrimaryKeys(null, "public", "users")) {
    while (rs.next()) {
        System.out.println("PK column: " + rs.getString("COLUMN_NAME")
                + " (name=" + rs.getString("PK_NAME") + ")");
    }
}

Foreign keys (imported keys = FKs from this table to others)

try (ResultSet rs = md.getImportedKeys(null, "public", "users")) {
    while (rs.next()) {
        System.out.println("FK " + rs.getString("FK_NAME")
                + ": " + rs.getString("FKCOLUMN_NAME")
                + " -> " + rs.getString("PKTABLE_NAME") + "." + rs.getString("PKCOLUMN_NAME"));
    }
}

Indexes

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class DatabaseMetadata5 {
    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {
            DatabaseMetaData md = conn.getMetaData();

            boolean unique = false; // set true to request only unique indexes
            boolean approximate = false;

            try (ResultSet rs = md.getIndexInfo(null, "public", "users", unique, approximate)) {
                while (rs.next()) {
                    String indexName = rs.getString("INDEX_NAME");
                    String column = rs.getString("COLUMN_NAME");
                    boolean nonUnique = rs.getBoolean("NON_UNIQUE");
                    short type = rs.getShort("TYPE"); // tableIndexStatistic / tableIndexClustered / etc.
                    if (indexName != null && column != null) {
                        System.out.println((nonUnique ? "IDX" : "UNIQUE") + " " + indexName + " on " + column + " type=" + type);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

7) “Dump the schema” pattern (tables → columns → keys)

For a basic schema inspection tool, you typically:

  1. getTables(...)
  2. For each table: getColumns(...)
  3. Optionally: getPrimaryKeys(...), getImportedKeys(...), getIndexInfo(...)

Keep it read-only; it’s metadata only.


8) Practical tips / pitfalls

  • Case sensitivity: If your DB stores identifiers uppercase, but you pass lowercase (or vice versa), you may get empty results. Check storesUpperCaseIdentifiers() / storesLowerCaseIdentifiers() and normalize.
  • Use % liberally while exploring: Start with schemaPattern="%" and narrow down once you see what the DB reports.
  • Some drivers are quirky: Not all metadata is perfectly implemented. When something looks missing, verify against the DB’s own system catalogs.
  • Close metadata ResultSets: They’re real JDBC resources. Use try-with-resources as shown.

How do I retrieve available catalogs in database?

By Wayan in JDBC Last modified: August 3, 2023 0 Comment

The examples below show you how to get the available catalog names in MySQL database. The available catalog names can be obtained from the DatabaseMetaData object by calling the getCatalogs() method. This method returns a ResultSet object. We iterate it and get the schema name by calling the getString() method and pass TABLE_CAT as the column name.

package org.kodejava.jdbc;

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

public class MetadataGetCatalog {
    private static final String URL = "jdbc:mysql://localhost";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

            // Gets DatabaseMetaData
            DatabaseMetaData metadata = connection.getMetaData();

            // Retrieves the schema names available in this database
            ResultSet rs = metadata.getCatalogs();

            while (rs.next()) {
                String catalog = rs.getString("TABLE_CAT");
                System.out.println("Catalog: " + catalog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Here is the list of catalog names available in the MySQL database:

Catalog: kodejava
Catalog: musicdb
Catalog: mysql
Catalog: performance_schema
Catalog: sys

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.1.0</version>
</dependency>

Maven Central

How do I get the maximum number of concurrent connections?

By Wayan in JDBC Last modified: May 31, 2024 0 Comment

This example shows you how to get the maximum number of concurrent connections to a database that are possible.
To get this information, we use the DatabaseMetaData.getMaxConnections() method call. If the return value is zero, it means that there is no limit or the limit is unknown.

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.DriverManager;

public class MaxConnections {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

            // Get database meta data.
            DatabaseMetaData metaData = connection.getMetaData();

            // Retrieves the maximum number of concurrent
            // connections to this database that are possible.
            // A result of zero means that there is no limit or
            // the limit is not known.
            int max = metaData.getMaxConnections();
            System.out.println("Max concurrent connections: " + max);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I get system functions supported by database?

By Wayan in JDBC Last modified: May 31, 2024 0 Comment
package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

public class SystemFunction {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            DatabaseMetaData meta = connection.getMetaData();

            // Get system functions supported by database
            String[] functions = meta.getSystemFunctions().split(",\\s*");

            for (String function : functions) {
                System.out.println("Function = " + function);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Here are MySQL database supported system functions.

Function = DATABASE
Function = USER
Function = SYSTEM_USER
Function = SESSION_USER
Function = PASSWORD
Function = ENCRYPT
Function = LAST_INSERT_ID
Function = VERSION

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I get date time functions supported by database?

By Wayan in JDBC Last modified: May 31, 2024 0 Comment
package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

public class DateTimeFunction {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            DatabaseMetaData meta = connection.getMetaData();

            // Get date and time functions supported by database
            String[] functions = meta.getTimeDateFunctions().split(",\\s*");

            for (String function : functions) {
                System.out.println("Function = " + function);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Date and time functions supported by MySQL database.

Function = DAYOFWEEK
Function = WEEKDAY
Function = DAYOFMONTH
Function = DAYOFYEAR
Function = MONTH
Function = DAYNAME
Function = MONTHNAME
Function = QUARTER
Function = WEEK
Function = YEAR
Function = HOUR
Function = MINUTE
Function = SECOND
Function = PERIOD_ADD
Function = PERIOD_DIFF
Function = TO_DAYS
Function = FROM_DAYS
Function = DATE_FORMAT
Function = TIME_FORMAT
Function = CURDATE
Function = CURRENT_DATE
Function = CURTIME
Function = CURRENT_TIME
Function = NOW
Function = SYSDATE
Function = CURRENT_TIMESTAMP
Function = UNIX_TIMESTAMP
Function = FROM_UNIXTIME
Function = SEC_TO_TIME
Function = TIME_TO_SEC

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I get numeric functions supported by database?

By Wayan in JDBC Last modified: May 31, 2024 0 Comment
package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

public class NumericFunction {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            DatabaseMetaData meta = connection.getMetaData();

            // Get numeric functions supported by database
            String[] functions = meta.getNumericFunctions().split(",\\s*");

            for (String function : functions) {
                System.out.println("Function = " + function);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Here are the numeric functions supported by MySQL database.

Function = ABS
Function = ACOS
Function = ASIN
Function = ATAN
Function = ATAN2
Function = BIT_COUNT
Function = CEILING
Function = COS
Function = COT
Function = DEGREES
Function = EXP
Function = FLOOR
Function = LOG
Function = LOG10
Function = MAX
Function = MIN
Function = MOD
Function = PI
Function = POW
Function = POWER
Function = RADIANS
Function = RAND
Function = ROUND
Function = SIN
Function = SQRT
Function = TAN
Function = TRUNCATE

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I get string functions supported by database?

By Wayan in JDBC Last modified: May 31, 2024 0 Comment
package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

public class StringFunction {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            DatabaseMetaData meta = connection.getMetaData();

            // Get string functions supported by database
            String[] functions = meta.getStringFunctions().split(",\\s*");

            for (String function : functions) {
                System.out.println("Function = " + function);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Here are the string functions supported by MySQL database:

Function = ASCII
Function = BIN
Function = BIT_LENGTH
Function = CHAR
Function = CHARACTER_LENGTH
Function = CHAR_LENGTH
Function = CONCAT
Function = CONCAT_WS
Function = CONV
Function = ELT
Function = EXPORT_SET
Function = FIELD
Function = FIND_IN_SET
Function = HEX
Function = INSERT
Function = INSTR
Function = LCASE
Function = LEFT
Function = LENGTH
Function = LOAD_FILE
Function = LOCATE
Function = LOCATE
Function = LOWER
Function = LPAD
Function = LTRIM
Function = MAKE_SET
Function = MATCH
Function = MID
Function = OCT
Function = OCTET_LENGTH
Function = ORD
Function = POSITION
Function = QUOTE
Function = REPEAT
Function = REPLACE
Function = REVERSE
Function = RIGHT
Function = RPAD
Function = RTRIM
Function = SOUNDEX
Function = SPACE
Function = STRCMP
Function = SUBSTRING
Function = SUBSTRING
Function = SUBSTRING
Function = SUBSTRING
Function = SUBSTRING_INDEX
Function = TRIM
Function = UCASE
Function = UPPER

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I get the max concurrent connection to a database?

By Wayan in JDBC Last modified: May 31, 2024 0 Comment
package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

public class MaxConcurrentConnection {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            DatabaseMetaData metadata = connection.getMetaData();

            // Get the information of maximum concurrent connection to the
            // database. The maximum number of active connections possible
            // at one time; a result of zero means that there is no limit
            // or the limit is not known.
            int maxConnection = metadata.getMaxConnections();
            System.out.println("Maximum Connection = " + maxConnection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

The result of the code snippet above:

Maximum Connection = 0

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I get database maximum table name length?

By Wayan in JDBC Last modified: May 31, 2024 0 Comment
package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

public class MaximumTableNameLength {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            DatabaseMetaData metadata = connection.getMetaData();

            // Get the information of database table name maximum length 
            int maxLength = metadata.getMaxTableNameLength();
            System.out.println("Max Table Name Length = " + maxLength);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

The result of the code snippet above is:

Max Table Name Length = 64

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I know if database support updatable result sets?

By Wayan in JDBC Last modified: May 31, 2024 0 Comment
package org.kodejava.jdbc;

import java.sql.*;

public class SupportUpdatableResultSet {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            DatabaseMetaData meta = connection.getMetaData();

            boolean updatable = meta.supportsResultSetConcurrency(
                    ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);

            System.out.println("Updatable ResultSet = " + updatable);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

The result of the code snippet above:

Updatable ResultSet = true

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

© 2026 Kode Java - Made with ♡ in Bali, Indonesia