Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does PreparedStatement.setNull requires sqlType?

Tags:

java

sql

jdbc

  1. According to the java docs of PreparedStatement.setNull: "Note: You must specify the parameter's SQL type". What is the reason that the method requires the SQL type of the column?

  2. I noticed that passing java.sql.Types.VARCHAR also works for non-varchar columns. Are there scenarios in which VARCHAR won't be suitable (certain column types or certain DB providers)?

Thanks.

like image 938
MosheElisha Avatar asked Nov 22 '10 08:11

MosheElisha


People also ask

What is the use of setString in Java?

setString. Sets the designated parameter to the given Java String value. The driver converts this to an SQL VARCHAR or LONGVARCHAR value (depending on the argument's size relative to the driver's limits on VARCHAR values) when it sends it to the database.

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.

Which methods on the PreparedStatement can be used to bind the parameters?

You must supply values for every parameter before executing the SQL statement. The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter.


1 Answers

According to the java docs of PreparedStatement.setNull: "Note: You must specify the parameter's SQL type". What is the reason that the method requires the SQL type of the column?

For maximum compatibility; as per the specification, there are some databases which don't allow untyped NULL to be sent to the underlying data source.

I noticed that passing java.sql.Types.VARCHAR also works for non-varchar columns. Are there scenarios in which VARCHAR won't be suitable (certain column types or certain DB providers)?

I don't think that sort of behaviour really is part of the specification or if it is, then I'm sure there is some sort of implicit coercion going on there. In any case, relying on such sort of behaviour which might break when the underlying datastore changes is not recommended. Why not just specify the correct type?

like image 109
Sanjay T. Sharma Avatar answered Sep 28 '22 06:09

Sanjay T. Sharma