建议在Java中使用PreparedStatement.setBoolean(1,Boolean.TRUE)?

rad*_*izi 1 java boolean jdbc

您能帮我找出PreparedStatement.setBoolean(1, Boolean.TRUE)和之间的最佳做法PreparedStatement.setBoolean(1, true)吗?

Era*_*ran 7

由于Boolean.TRUE是类型Boolean,并且

void setBoolean(int parameterIndex, boolean x) throws SQLException;
Run Code Online (Sandbox Code Playgroud)

需要一个boolean,使用起来更有意义setBoolean(1, true),以避免不必要的拆箱。

  • @radhwenhrizi:驱动程序随后如何处理该值并不重要。参数采用原始“布尔值”这一事实意味着,如果您传递的是“布尔值”,则需要先将其拆箱。因此,当你有选择时直接传递“boolean”显然更好。 (2认同)

T.J*_*der 7

两者都有效,但请注意setBoolean接受boolean,而不是BooleanTRUEBoolean(的包装对象true)。没有理由使用包装器setBoolean,只需boolean通过booleanValue方法将其自动拆箱到。除非您有强烈的风格理由要使用不必要的包装对象,否则请使用true,而不要Boolean.TRUE使用。


在评论中,您说过:

我在java doc中找到了“驱动程序将其发送到数据库时将其转换为SQL BIT或BOOLEAN值”。因此最好使用Boolean.TRUE

No, the SQL type that gets used by the driver doesn't have anything to do with this. It has to do with what the setBoolean method signature says. The method signature says it accepts a boolean, so that's what it will see. The only reason using Boolean.TRUE works is that before calling setBoolean, the compiler outputs code to call booleanValue() on Boolean.TRUE to get its equivalent boolean value (true). In fact, this:

ps.setBoolean(1, Boolean.TRUE);
Run Code Online (Sandbox Code Playgroud)

and this:

ps.setBoolean(1, Boolean.TRUE.booleanValue());
Run Code Online (Sandbox Code Playgroud)

produce identical bytecode, which looks something like this:

21: getstatic     #6         // Field java/lang/Boolean.TRUE:Ljava/lang/Boolean;
24: invokevirtual #7         // Method java/lang/Boolean.booleanValue:()Z
27: invokeinterface #8,  3   // InterfaceMethod java/sql/PreparedStatement.setBoolean:(IZ)V

Better to use

ps.setBoolean(1, true);
Run Code Online (Sandbox Code Playgroud)

so there's no need for that extra call (although it will get optimized away fairly quickly if needed).