0

I have this code that converts a JDBC result set into a list of hash tables:

private static ArrayList<HashMap<String, Object>> convertResultSet(ResultSet resultSet) throws SQLException {
    ArrayList<HashMap<String, Object>> map = new ArrayList<HashMap<String, Object>>();
    ResultSetMetaData rsmd = resultSet.getMetaData();
    int nColumns = rsmd.getColumnCount();
    while(resultSet.next()) {
        HashMap<String, Object> hash = new HashMap<String, Object>();
        for (int i = 0; i < nColumns; i++)
        {
            hash.put(rsmd.getColumnName(i), resultSet.getObject(i));
        }
        map.add(hash);
    }
    return map;
}

but when run, it throws a "Column index out of range." exception.

Any ideas?

Dabloons
  • 1,462
  • 2
  • 17
  • 30

1 Answers1

4

As stated in the javadoc, the index for the getColumnName(i) starts from 1, not from 0.

Leo
  • 6,480
  • 4
  • 37
  • 52
  • @Dabloons I think this is caused by historical reasons, see http://stackoverflow.com/questions/616135/in-jdbc-why-do-parameter-indexes-for-prepared-statements-begin-at-1-instead-of – Leo Sep 22 '14 at 21:50
  • All indexes in the SQL Standard and in JDBC are 1-based. The fact that indexes in most languages these days are 0-based is largely due to languages like C and pointer manipulation. – Mark Rotteveel Sep 23 '14 at 07:37