简体   繁体   English

如何逃避使用PreparedStatement.setNull?

[英]How to escape from use PreparedStatement.setNull?

I have a very big table in my DataBase. 我的数据库中有一个很大的表。 Some of they fields may be null. 其中一些字段可能为空。

I just want to escape from use the: 我只想逃避使用:

PreparedStatement.setNull(index, Type.X)

Like: 喜欢:

if(obj.getSomaData() == null){
  insertStmt.setNull(++i, java.sql.Types.VARCHAR);
}else{
  insertStmt.setString(++i, obj.getSomaData());
}

There's a better and cleaner way to do this? 有更好更好的方法吗?

PS: I'm using PostgreSQL. PS:我正在使用PostgreSQL。

The primary use case of setNull is for setting primitive types to null, and to handle some edge cases where the driver can't know the data types of the parameters and needs to be explicitly instructed. setNull的主要用例是将原始类型设置为null,并处理一些驱动程序无法得知参数数据类型且需要明确指示的极端情况。

In most cases you should be able to use setString(idx, null) (or a setXXX of another object type) just fine. 在大多数情况下,您应该可以使用setString(idx, null) (或其他对象类型的setXXX )。

To quote JDBC 4.2 section 13.2.2.4: 引用JDBC 4.2第13.2.2.4节:

If a Java null is passed to any of the setter methods that take a Java object, the parameter will be set to JDBC NULL . 如果将Java null传递给采用Java对象的任何setter方法,则该参数将设置为JDBC NULL

An exception is made for an 'untyped' null (eg using setObject ), where it is suggested that for maximum portability you should use setNull or the setObject that takes a type parameter as not all database support that without type information. 对于“未类型化”的null (例如,使用setObject )有一个例外,建议为最大的可移植性,应使用setNull或带有类型参数的setObject ,因为并非所有数据库都支持无类型信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM