java.sql.SQLException: Column index out of range.

时间:2024-02-17 14:56:36
    public <E> List<E> selectList(Mapper mapper, Connection conn) {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            String queryString = mapper.getQueryString();
            String resultType = mapper.getResultType();
            Class domainClass = Class.forName(resultType);
            pstm = conn.prepareStatement(queryString);
            rs = pstm.executeQuery();
            List<E> list = new ArrayList<E>();
            while (rs.next()) {
                E obj = (E) domainClass.newInstance();
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnCount = rsmd.getColumnCount();
                System.out.println(columnCount);
                for (int i = 0; i <= columnCount; i++) {
//获取每列的名
                    String columnName = rsmd.getColumnName(i);
//获取每列值
                    Object columnValue = rs.getObject(columnName);
//给obj赋值,使用的是java内省机制(借助PropertyDescriptor实现属性的封装)
                    PropertyDescriptor pd = new PropertyDescriptor(columnName, domainClass);
                    Method writeMethod = pd.getWriteMethod();
                    writeMethod.invoke(obj, columnValue);
                }
                list.add(obj);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

 

这样会报错
java.sql.SQLException: Column index out of range.
 
解决办法
数组越界了,尝试更改fori循环