java获取数据库列的别名,JDBC ResultSet获取具有表别名的列

Imagine I have a query like

SELECT * from table1 a, table2 b where (WHATEVER)

Maybe both tables have the same column name. So I though it would be nice to access the data via

resultSet.getString("a.columnName");

resultSet.getString("b.columnName");

But this backfires on me and I get nothing. I read the API, but they don't really talk about this case. Is such a feature vendor dependent?

解决方案

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

You have two options:

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)

then in your java code refer to the column aliases:

resultSet.getString("columnNameA");

resultSet.getString("columnNameB");

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

resultSet.getString(1);

resultSet.getString(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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值