How to get an Integer from a Java resultset

By default, ResultSet.getInt(...) only returns an int. If the database value is null, it will return 0. This is already covered in the documentation: “The default for ResultSet.getInt when the field value is NULL is to return 0″. This is also the case for resultset.getFloat().

This irritating behavior can easily be fixed with the wasNull method:

Integer myInt = resultSet.getInt("nullable_column"); //Returns 0 even if the value should be null
if (resultSet.wasNull()) {
    myInt = null;

This way, your resultSet.getInt(...) will correctly set null values instead of returning 0.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see