有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSQLPostgre介绍了如何在联接后重命名每个列,因为它们的字段太多

我想连接两个表并读取java中的所有列。在java中,resultset包含所有字段,但两个表的字段名称相同。 它们大约有65列,我不想在select之后指定每一列

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读取字段

我是否可以重命名表中的每个字段,而不在select之后指定每个列?(如“选择a.name作为a_名称,选择b.name作为b_名称,…”)

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


共 (1) 个答案

  1. # 1 楼答案

    您可以使用列编号而不是列名。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));
    }