0

I have an sql column PROTOCOL of Number type .It is nullable and a constraint on the table PROTOCOL IN(1,2,3).I am able to set to null. How to get the value if its null? I can do rs.getInt() but I dont think it returns null?

if(protocol==0)
            {

               stmt.setNull(15, java.sql.Types.INTEGER);                

           }
            else{
            stmt.setInt(15, protocol);
            }
constantlearner
  • 5,157
  • 7
  • 42
  • 64
  • duplicate of http://stackoverflow.com/questions/2920364/checking-for-a-null-int-value-from-a-java-resultset – Hui Zheng Jan 25 '13 at 11:09

2 Answers2

4

Use wasNull() method.

 Integer myValue = rs.getInt(15);
 if (rs.wasNull()) {
   myValue = null;
 }
SJuan76
  • 24,532
  • 6
  • 47
  • 87
  • If the value is null what will the myValue be here doesn't it throw exception? Integer myValue = rs.getInt(15); – constantlearner Jan 25 '13 at 11:09
  • 1
    (http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getInt(java.lang.String)) says that it will be 0. – SJuan76 Jan 25 '13 at 11:11
  • I can also try...... Integer myValue = rs.getInt(15); if (rs==0) { myValue = null; } – constantlearner Jan 25 '13 at 11:14
  • 1
    (I suppose you meant `if(myValue==0)`) - You can then not distinguish between `0` and `null`, but according to your constraint that might do it. I would still prefer an explicit handling of the `NULL` value, though. – Andreas Fester Jan 25 '13 at 11:15
3

I can do rs.getInt() but I dont think it returns null?

Use ResultSet.wasNull() after getInt() to check if the last column read was NULL.

Or, use ResultSet.getObject() instead of getInt(), which returns null if the column is NULL.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123