Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreparedStatement setNull(..)

Java PreparedStatement provides a possibility to explicitely set a Null value. This possibility is:

prepStmt.setNull(parameterIndex, Types.VARCHAR); 

Are the semantics of this call the same as when using a specific setType with a null parameter?

prepStmt.setString(null); 

?

like image 434
paweloque Avatar asked Aug 31 '09 13:08

paweloque


People also ask

What is PreparedStatement interface for?

The PreparedStatement interface extends the Statement interface it represents a precompiled SQL statement which can be executed multiple times. This accepts parameterized SQL quires and you can pass 0 or more parameters to this query.

What is meant by PreparedStatement?

The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.

When should a PreparedStatement be closed?

Closing PreparedStatement Object A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup.


2 Answers

but watch out for this....

Long nullLong = null;  preparedStatement.setLong( nullLong ); 

-thows null pointer exception-

because the protype is

setLong( long )    

NOT

setLong( Long ) 

nice one to catch you out eh.

like image 144
Owen Avatar answered Sep 22 '22 12:09

Owen


This guide says:

6.1.5 Sending JDBC NULL as an IN parameter

The setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.

A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified.

So yes they're equivalent.

like image 20
djna Avatar answered Sep 21 '22 12:09

djna