Wednesday, September 14, 2016

A generic method to get column-value map from Java JDBC ResultSet

The following method creates a column_name to value map from the Java JDBC ResultSet. It makes use of the meta data and Spring JdbcUtils class.

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.LinkedCaseInsensitiveMap;

public Map getColumnValueMapFromResultSet(ResultSet resultSet)
   throws SQLException {
  ResultSetMetaData metaData = resultSet.getMetaData();
  int columnCount = metaData.getColumnCount();
  Map columnValueMap = new LinkedCaseInsensitiveMap(columnCount );

  for (int i = 1; i <= columnCount; i++) {
   String columnName = JdbcUtils.lookupColumnName(metaData, i);
   Object value = JdbcUtils.getResultSetValue(resultSet, i);
   columnValueMap.put(columnName, value);
  }
  return columnValueMap;
 }

No comments:

Post a Comment