Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting null to an Integer column using JDBC

Tags:

java

sql

jdbc

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); 
like image 612
constantlearner Avatar asked Jan 25 '13 02:01

constantlearner


People also ask

Can we insert NULL in integer column?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints.

How do I insert a NULL into a column?

You also can specify the NULL keyword in the VALUES clause to indicate that a column should be assigned a NULL value. The following example inserts values into three columns of the orders table: INSERT INTO orders (orders_num, order_date, customer_num) VALUES (0, NULL, 123);


2 Answers

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.

like image 89
Smit Avatar answered Sep 18 '22 06:09

Smit


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); } 
like image 44
Qw3ry Avatar answered Sep 19 '22 06:09

Qw3ry