Tuesday, July 5, 2011

Working with ResultSets

If you do not know exactly the table structure (the schema) of the ResultSet, you can obtain it via a ResultSetMetaData object.

ResultSetMetaData rsmd = rs.getMetaData() ;
int colCount = rsmd.getColumnCount() ;

for (int i = 1 ; i <= colCount ; i++)
{
    if (i > 1)
        out.print(", ");
    out.print(rsmd.getColumnLabel(i)) ;
}
out.println() ;
Once a ResultSet has been obtained, you can step through it to obtain its rows, or, more specifically, the fields of its rows:
while (rs.next())
{
    for (int i = 1 ; i <= colCount ; i++)
    {
        if (i > 1)
        out.print(", ");
        out.print(rs.getObject(i)) ;
    }
    out.println() ;
}
Note that the column numbers start at 1, not 0 as in Java arrays. More conveniently, if slightly less efficiently, there is a getObject method for ResultSet which takes a String argument containing the column name. There are also getxxx methods that take the String name of the column instead of the column number. Thus the above code could have been written:
while (rs.next())
{
    out.println(rs.getObject("CustomerID")   + ", " +
                rs.getObject("CustomerFirstName") + ", " +
                rs.getObject("CustomerLastName")  + ", " +
                rs.getObject("CustomerAddress") ) ;
}
Instead of getObject, you can use type specific methods, getInt, getString, etc. However, these have a major disadvantage: if the field is of primitive type such as int, float etc., then if the field is actually null in the database, then there is no value that can be returned that is indistinguishable from some valid value. There is a mechanism for finding out whether the last value obtained was really null or not: wasNull, but this must be called immediately after the getXxx method and before the next such call. If you use getObject, then if the field was null then the object value returned will be null so you can pass this value around and check for it at your convenience. Note also that printing is the most common thing to do with retrieved values, and passing a null to print will print the string "null". Thus for many cases no extra processing of nulls will be necessary.

No comments:

Post a Comment

Chitika