46

I have an sql column PROTOCOL, it is nullable and has a constraint on the table

PROTOCOL IN (1, 2, 3)

Also since it is nullable, I want to set and get null values into table

But I cannot do setInt and getInt as null. How to set a null to column as null using JDBC

setInt(4,null);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
constantlearner
  • 5,157
  • 7
  • 42
  • 64

2 Answers2

95

Try using.

   pst.setNull(4, java.sql.Types.INTEGER);  //pst is prepared statement instance.

Interface PreparedStatement.setNull API

Mapping of java.sql.Types to SQL types

P.S. : Edited to reflect Java 8 updates.

Smit
  • 4,685
  • 1
  • 24
  • 28
28

In addition to Smit's answer:

If you want to insert an Integer-object into a database that may be null, you can use

statement.setObject(4, yourObject, java.sql.Types.INTEGER);

instead of

if (yourObject == null) {
    statement.setNull(4, java.sql.Types.INTEGER);
else {
    statement.setInt(4, yourObject);
}
Qw3ry
  • 1,319
  • 15
  • 31