Java JDBC ResultSet metadata FAQ: How do I dynamically determine the number of columns in a Java/JDBC ResultSet?
When you send a SQL SELECT statement to a database using JDBC, you’ll read the query results into a JDBC ResultSet object. We demonstrated how to do this in our article on How to Create and Execute a SQL SELECT Query. In some database programs you’ll need to go a bit further, and dynamically determine the number of columns that are in a Java ResultSet object. As an example, I’ve been working on a Contact Management servlet-based Intranet application. Because I can dynamically determine the number of columns returned from my queries, I can write one QueryServlet to handle all of my database query needs. This makes it very easy to create a simple report writer for my Intranet app. The way you accomplish this is by working with the Java JDBC metadata.