JDBC ResultSet get columns with table alias

后端 未结 7 964
春和景丽
春和景丽 2020-11-28 13:22

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

7条回答
  •  鱼传尺愫
    2020-11-28 13:40

    If you are using MySQL just add

    &useOldAliasMetadataBehavior=true
    

    to your connectionString.

    Afterwards you can use this little Helper:

    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.util.HashMap;
    import java.util.Map;
    
    public class ResultSetHelper {
    
        private final Map columnMap;
    
        public ResultSetHelper(ResultSet rs) throws SQLException {
            this.columnMap = new HashMap<>();
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            for (int index = 1; index <= columnCount; index++) {
                String columnName = md.getColumnLabel(index);
                if (!columnMap.containsKey(columnName)) {
                    columnMap.put(columnName, index);
                }
    
                String tableAlias = md.getTableName(index);
                if (tableAlias != null && !tableAlias.trim().isEmpty()) {
                    columnMap.put(tableAlias + "." + columnName, index);
                }
            }
        }
    
        public Integer getColumnIndex(String columnName) {
            return columnMap.get(columnName);
        }
    
        public Integer getColumnIndex(String tableAlias, String columnName) {
            return columnMap.get(tableAlias + "." + columnName);
        }
    
    }
    

提交回复
热议问题