How Do You Retrieve the Column Types from a ResultSet? JDBC

In GUI database applications, you must determine the type of a ResultSet’s columns in order to validate column values before sending them to the database server. So, to retrieve the column data type from a result set object, let’s return the result as a java.util.List, where each element of the list is a java.lang.String, which represents a data type.

The Solution: getTypes()

/**
* Get the column data type from a result set object.
* @param rs a ResultSet object to process
* @throws SQLException Failed to get data types from a ResultSet
* @return the result as a java.util.List, where each element of the
* list is a String object (designates types).
*/
public static java.util.List getTypes(ResultSet rs)
throws SQLException {
if (rs == null) {
return null;
}
ResultSetMetaData meta = rs.getMetaData();
if (meta == null) {
return null;
}
java.util.List types = new java.util.ArrayList();
for (int i = 1; i <= meta.getColumnCount(); i++){
String columnType = meta.getColumnTypeName(i);
types.add(columnType);
}
return types;
}

Discussion

  • The solution presented is a general one: this solution can be applied to any ResultSet object.
  • ResultSetMetaData.getColumnCount() returns the total number of columns for a ResultSet object.
  • ResultSetMetaData.getColumnTypeName(i) returns the column data type name for the ith position (positions start from 1).

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

JDBC Topics