Why does PreparedStatement.setNull requires sqlType?

前端 未结 3 1939
小蘑菇
小蘑菇 2021-01-01 16:56
  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 t

相关标签:
3条回答
  • 2021-01-01 17:22

    When it comes to Oracle it would be very unwise to use varchar2 towards other datatypes. This might fool the optimizer and you could get an bad execution plan. For instance filtering on a date column using a timestamp datatype in your bind, Oracle could end up reading all your rows converting all dates to timestamp, then filtering out the wanted rows. If you have a index on your date column, it could even get worse (if oracle chose to use it) - doing single reads on your oracle blocks.

    --Lasse

    0 讨论(0)
  • 2021-01-01 17:33

    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?

    0 讨论(0)
  • 2021-01-01 17:46

    JDBC drivers appear to be moving away from setNull. See Add support for setObject(<arg>, null).

    My list of databases supporting the more logical behaviour is:

    1. Oracle
    2. MySQL
    3. Sybase
    4. MS SQL Server
    5. HSQL

    My list of databases NOT supporting this logical behaviour is:

    1. Derby Queries with guarded null Parameter fail
    2. PostgreSQL Cannot pass null in Parameter in Query for ISNULL Suggested solution
    0 讨论(0)
提交回复
热议问题