Alessandro Lacava’s Blog

Google
 

December 12, 2007

How to get the number of columns in a ResultSet in Java

Filed under: Computer, Java, Database — alessandrolacava @ 12:32 pm

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

JAVA:
  1. // Here you get the conn object. E.g.:
  2. // Connection conn = DriverManager.getConnection(...);
  3.  
  4. Statement st = conn.createStatement();
  5. ResultSet rs = st.executeQuery("SELECT * FROM your_table");
  6. ResultSetMetaData rsmd = rs.getMetaData();
  7. int numCols = rsmd.getColumnCount();
  8. System.out.println("Number of columns in your_table: " + numCols);

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