Search code examples
javasqlresultset

Java: How to retrieve SQL resultSet data through column name?


I wanted to retrieve the data stored in resultSet through the column names and the index of the row. Is there any way to do that? I tried through arraylist but I was not able to do that.

Example: There is table called Employee which has around 20 records with several columns such as ID, Name, Account, Project, Shift and Role. I want to access the data from the column 'Name' and 'Role' from the 5th row of resultSet i.e., something like (Name, 5) and (Row, 5). The column name will be taken from the user input. So I want to retrieve the data through column name. Is there any way to do that?


Solution

  • Interface java.sql.ResultSet has a collection of getter functions. The pattern is

    getXxx(int columnIndex)
    getXxx(String columnLabel)
    

    Where Xxx is the data type to be fetched. The second variant fetches a value using the column header label.

    To adust the cursor to a specific row, the function is

    absolute(int rownum)
    

    If the call returns false it means there are no rows at that number. Caveat, not all drivers and queries allow navigation to any row number like that.