且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JDBC ResultSet获取具有表别名的列

更新时间:2022-12-17 17:29:04

JDBC将根据查询中指定的内容命名列 - 它不是了解表名等。

JDBC will simply name the columns by what is specified in the query - it doesn't know about table names etc.

您有两种选择:

选项1:在查询中以不同方式命名列,即

Option 1: Name the columns differently in the query, ie

SELECT
    a.columnName as columnNameA,
    b.columnName as columnNameB,
    ...
from table1 a, table2 b where (WHATEVER)

然后在你的java代码中引用列别名:

then in your java code refer to the column aliases:

resultSet.getString("columnNameA");
resultSet.getString("columnNameB");



选项2:请参阅调用JDBC API时列位置


Option 2: Refer to the column position in your call to the JDBC API:

resultSet.getString(1);
resultSet.getString(2);

请注意,JDBC API使用基于一个的索引 - 即它们计数来自 1 (不是来自 0 ,如java索引),因此请使用 1 $ c第一列为$ c>,第二列为 2

Note that the JDBC API uses one-based indexes - ie they count from 1 (not from 0 like java indexes), so use 1 for the first column, 2 for the second column, etc



我建议选项1,因为引用命名列更安全:有人可能会更改查询中列的顺序,它会默默地破坏您的代码(您将访问错误的列但不知道),但是如果他们改变列名,你至少会在运行时获得没有这样的列异常。


I would recommend option 1, because it's safer to refer to named columns: Someone may change the order of the columns in the query and it would silently break your code (you would be accessing the wrong column but would not know), but if they change the columns names, you'll at least get a "no such column" exception at runtime.