How to get the number of columns from a JDBC ResultSet?

Jonas picture Jonas · Apr 10, 2010 · Viewed 126k times · Source

I am using CsvJdbc (it is a JDBC-driver for csv-files) to access a csv-file. I don't know how many columns the csv-file contains. How can I get the number of columns? Is there any JDBC-function for this? I can not find any methods for this in java.sql.ResultSet.

For accessing the file, I use code similar to the example on the CsvJdbc website.

Answer

Roman picture Roman · Apr 10, 2010

You can get columns number from ResultSetMetaData:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();

int columnsNumber = rsmd.getColumnCount();