我在一些 Java 代码中发现了一个 SQL 查询,如下所示:
SELECT * FROM tableA JOIN tableB ON ...
tableA
和 tableB
都包含名为 id
的字段,执行此查询的 Java 代码执行以下操作:
Integer id = (Integer)rs.getObject("id");
JDBC 规范对于返回哪个字段值有什么规定吗?我找不到任何可以这样或那样说的东西。我看到一些数据库throw an error但MySQL/MariaDB(此处使用的数据库)不会提示,返回的值似乎是tableA.id,或者名称为“id”的“最左边”字段。
我问的是在这种情况下是否存在规范定义的行为,或者是否由数据库和/或 JDBC 驱动程序来决定如何行为。
不用说,当我查看代码时,我将修复这个问题,使其能够可预测且明确地工作,但我很好奇答案。
最佳答案
ResultSet
的API文档回答你的问题:
Column names used as input to getter methods are case insensitive. When a getter method is called with a column name and several columns have the same name, the value of the first matching column will be returned.
JDBC 4.3 specification第 15.2.3 节中的文档检索值还指出:
The columns are numbered from left to right, as they appear in the select list of the query, starting at 1.
Column labels supplied to getter methods are case insensitive. If a select list contains the same column more than once, the first instance of the column will be returned.
The index of the first instance of a column label can be retrieved using the method
findColumn
. If the specified column is not found, the methodfindColumn
throws anSQLException
.
因此,如果结果集具有多个具有相同名称(不区分大小写(!))的列,则返回第一个匹配列的值。
关于java - JDBC 规范是否定义了如果您对列名冲突的查询调用 `ResultSet.getObject(String)` 会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58090160/