49

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);
4
  • 3
    Have you tried the setObject() method? Commented Jan 25, 2013 at 2:55
  • 2
    Try setObject(4, null). Commented Jan 25, 2013 at 3:06
  • @BheshGurung Bah, beat me to it =p Commented Jan 25, 2013 at 3:06
  • 1
    How can i get it after setting to null ;Will getInt Return null? Commented Jan 25, 2013 at 10:56

2 Answers 2

96

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How can i get it after setting to null ;Will getInt Return null?
@constantlearner I never had a occasion to use this, but surely you can try.
@Code-Apprentice only if you know in advance you want to insert null.
30

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);
}

5 Comments

new in java8? statement.setObject(4, yourObject, java.sql.JDBCType.INTEGER);
You actually don't need to provide the JDBCType | sql.Types jdbc figures it out by itself. Or at least the MSSQL driver does.
In DB2, this won't work: java.sql.SQLFeatureNotSupportedException: setObject not implemented
@Jaja are you referring to my answer, or to the comment from Marthinus Engelbrecht?
@Qw3ry, NOT referring to your answer, I mean, there should be java.sql.Types instead of java.sql.JDBCType

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.