在 java 中准备语句时使用 long 而不是 int 有什么缺点吗?

Is there any drawback of using long instead of int when preparing a statement in java?

如果我使用 PreparedStatement.setLong 作为参数,其对应的数据库列实际上是 MySql integer,传递 int 显然会看到它在 [= 中自动加宽25=]。但是在 jdbc 的 "lower" 级别中,这有什么关系吗?如果我希望 db 列的数据类型在不久的将来更改为 biginteger,使用 long 可以避免额外的工作吗?

编辑: 我的意思是设置 long 的方法总是收到一个 int,所以我不会不小心传递一个值对于数据库列来说太大了。

从 100% 正式的角度来看,对 INTEGER 列使用 setLong 可能是不安全的。 JDBC 4.3 规范说 setXXX 方法(setObject 除外)遵循附录 B.2 的映射,其中表示 Java long映射到 SQL BIGINT。然后,它取决于驱动程序或数据库是否可以将 BIGINT 值与 INTEGER 列一起使用。

关于此事的 JDBC 1.20 规范说:

7.2.1 Data type conformance on IN parameters

The PreparedStatement.setXXX methods do not perform any general data type conversions. Instead the Java value is simply mapped to the corresponding SQL type (following the mapping specified in Table 3 on page 28) and that value is sent to the database.

It is the programmer’s responsibility to make sure that the java type of each argument maps to a SQL type that is compatible with the SQL data type expected by the database. For maximum portability programmers, should use Java types that correspond to the exact SQL types expected by the database.

If programmers require data type conversions for IN parameters, they may use the PreparedStatement.setObject method which converts a Java Object to a specified SQL type before sending the value to the database.

最近的 JDBC 规范中不再出现此措辞,但其意图仍然适用,并由 JDBC 4.3 中的附录 B.2 定义。

然而,实际上,许多 JDBC 驱动程序 - 包括 MySQL Connector/J - 支持更广泛的转换,类似于为 setObject 定义的转换在附录 B.5 中,尽管每个驱动程序在这里都有其注意事项和怪癖。对于 Long,这意味着 getObject 可以定位 TINYINTSMALLINTINTEGERBIGINTREALFLOAT , DOUBLE, DECIMAL, NUMERIC, BIT, BOOLEAN, CHAR, VARCHAR, LONGVARCHAR, 和那 - 通常 - 意味着你也可以用 setLong 做同样的事情。

这也为附录 B.6 中定义的 getLong 的转换提供了统一性。

它是否有任何缺点,取决于实现。 MySQL Connector/J 驱动程序是开源的,因此如果您想了解具体细节:查看源代码。

但是,如果您的应用程序实际使用 long,为什么数据库类型是 INTEGER?在您的数据库中使用 BIGINT 来匹配您的应用程序,或者在您的应用程序中使用 int 来匹配数据库。