Search code examples
javajdbccsvresultset

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


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.


Solution

  • You can get columns number from ResultSetMetaData:

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