Search code examples
javaservletsjdbcresultset

How to view what is inside database JDBC ResultSet in java


I am getting an error saying that some string is missing inside the ResultSet returned from the database. Now I have a problem: how can I see what is inside the ResultSet?

Examples available on google are with explicit methods like getString() or getInt() but thse methods suppose you know what you are looking for. What I actually need - to look what elements are available inside my ResultSet.

Something like when I issue the resultSet.toString() command, and it would show me some kind of map with variable names - is it possible?

EDIT:

If it is useful - below is a piece of code:

public Project mapRow(ResultSet resultSet, int i) throws SQLException {
        System.out.println(resultSet.toString());
        return new Project(resultSet.getInt("project_id"), resultSet.getString("project_name"),
                            resultSet.getString("project_description"), new Category(resultSet.getInt("category_id"),
                                                                                    resultSet.getString("category_name")),
                            resultSet.getString("project_link"), resultSet.getString("project_qa"));
    }

Error:

Caused by: org.postgresql.util.PSQLException: The column name category_id was not found in this ResultSet.

Solution

  • The ResultSet contains no element after you execute a statement. To get the first row of information, you need to do rs.next().

    Here is a simple iteration through the ResultSet values.

    boolean hasValue = false;
    while(resultSet.next())
    {
        hasValue = true;
        out.println(resultSet.getString("column_name");
        out.println(resultSet.getInt("column_name");
    }
    if(hasValue)
        out.println("Result set has values inside of it");
    else out.println("Result set has no values inside of it");
    

    As long as you have some values inside your resultSet variable, you need to iterate it to get the next value. By default, after the query is executed, you have no value inside of it because it might have no value.

    Edit:

    ResultSetMetaData metaData = resultSet.getMetaData();
    int count = metaData.getColumnCount(); //number of column
    String columnName[] = new String[count];
    
    for (int i = 1; i <= count; i++)
    {
       columnName[i-1] = metaData.getColumnLabel(i)); 
    }
    

    This gives you the column names, if this is what you want.