shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.walker.jdbc;
 
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 时克英 2020/12/08
 */
public class ResultSetUtils {
    /**
     * 与mapRow配套使用,存储columnName,columnIndex
     */
    private Map<String,Integer> columnMap;
    /**
     *
     * @param rs
     * @param column
     * @return columnIndex, 从1开始
     * @throws SQLException
     */
    public int findColumn(ResultSet rs, String column) throws SQLException {
        if(this.columnMap == null) {
            columnMap = new HashMap<>();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            for(int index = 1; index <= columnCount; ++index) {
                this.columnMap.put(this.lookupColumnName(rsmd, index).toUpperCase(), index);
            }
        }
        Integer columnIndex = null;
        columnIndex = this.columnMap.get(column.toUpperCase());
        if(columnIndex == null) {
            columnIndex = -1;
        }
        return columnIndex;
    }
 
    private String lookupColumnName(ResultSetMetaData resultSetMetaData, int columnIndex) throws SQLException {
        String name = resultSetMetaData.getColumnLabel(columnIndex);
        if (name != null && !name.isEmpty()) {
            name = resultSetMetaData.getColumnName(columnIndex);
        }
        return name;
    }
}