Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

How to Get the Number of Columns In a ResultSet In Java

In Java it is possible to retrieve the number of columns of a ResultSet dinamically, thanks to the ResultSetMetaData class. Here’s an example:

1
2
3
4
5
6
7
8
// Here you get the conn object. E.g.:
// Connection conn = DriverManager.getConnection(...);

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM your_table");
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
System.out.println("Number of columns in your_table: " + numCols);

The previous code retrieves and displays the number of columns of your_table.

Comments