ResultSetMetaData lets you inspect the shape of a SQL query result at runtime — for example:
- how many columns were returned
- each column’s name and label
- its SQL type
- table/schema info if available
- whether values can be null, are auto-incremented, etc.
Basic usage
package org.kodejava.jdbc;
import java.sql.*;
public class MetaDataExample {
public static void main(String[] args) throws Exception {
String url = "jdbc:postgresql://localhost:5432/postgres";
String user = "postgres";
String password = "postgres";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement ps = conn.prepareStatement("SELECT id, name, created_at FROM users");
ResultSet rs = ps.executeQuery()) {
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
System.out.println("Column " + i);
System.out.println(" Name: " + meta.getColumnName(i));
System.out.println(" Label: " + meta.getColumnLabel(i));
System.out.println(" Type: " + meta.getColumnTypeName(i));
System.out.println(" Java Type: " + meta.getColumnClassName(i));
System.out.println(" Table: " + meta.getTableName(i));
System.out.println(" Nullable: " + meta.isNullable(i));
System.out.println(" Auto Increment: " + meta.isAutoIncrement(i));
}
}
}
}
Common methods
getColumnCount()— number of columnsgetColumnName(i)— actual database column namegetColumnLabel(i)— alias from SQL, if presentgetColumnType(i)— JDBC type constantgetColumnTypeName(i)— database-specific type namegetColumnClassName(i)— Java class typically usedgetTableName(i)— table name, if the driver provides itisNullable(i)— whether the column may containNULLisAutoIncrement(i)— whether it’s auto-generatedgetPrecision(i)/getScale(i)— numeric size detailsisReadOnly(i)— whether the column is read-only
Important note: names vs labels
If your query uses aliases:
SELECT first_name AS name FROM users
Then:
getColumnName(1)may returnfirst_namegetColumnLabel(1)returnsname
If you want what the query “shows” to the user, prefer getColumnLabel().
Example: print a result set dynamically
try (ResultSet rs = ps.executeQuery()) {
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
String label = meta.getColumnLabel(i);
Object value = rs.getObject(i);
System.out.println(label + " = " + value);
}
System.out.println("---");
}
}
Why this is useful
Use ResultSetMetaData when:
- you don’t know the query columns in advance
- you’re building a generic table printer/exporter
- you need to map query results dynamically
- you’re debugging SQL joins or aliases
