gpt4 book ai didi

java - SQL postgres - 如何在连接后重命名每列,因为它们的字段太多

转载 作者:行者123 更新时间:2023-12-01 09:26:51 27 4
gpt4 key购买 nike

我想连接两个表并读取 java.lang.Data 中的所有列。在 java 中,结果集包含所有字段,但两个表的名称相同。它们大约有 65 列,我不想在选择后指定每一列。

SQL查询:

select * from Tab a join Tab b on a.id = b.id;

在java中我想要:

private MyObject map(ResultSet rs) throws SQLException {
myObj.setNameA(rs.getString("a_name"));
myObj.setNameB(rs.getString("b_name"));
}

我的想法是用表的变量重命名每一列,例如“a_name”和“b_name”,然后在java中读取字段。

我可以重命名表的每个字段而不指定选择后的每一列吗? (例如“选择a.name作为a_name,b.name作为b_name,...”)

或者他们有更好的解决方案来获取java中的所有列吗?

最佳答案

您可以使用列号代替列名称。 Javadoc 明确指出 ( http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html )

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. The column name option is designed to be used when column names are used in the SQL query that generated the result set. For columns that are NOT explicitly named in the query, it is best to use column numbers. If column names are used, the programmer should take care to guarantee that they uniquely refer to the intended columns, which can be assured with the SQL AS clause.

当然,使用列号需要知道列的确切位置(从 1 开始)。

private MyObject map(ResultSet rs) throws SQLException {
myObj.setNameA(rs.getString(1));
myObj.setNameB(rs.getString(66));
}

关于java - SQL postgres - 如何在连接后重命名每列,因为它们的字段太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39764482/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com