Displaying Column names fromJDBC Resultset

Hi All,

The below example will demonstrate how to display column name from ResultSet object, This is very useful when we are building something very generic to display data on the UI. By using ResultSetMetaData , which  contains information about the columns of the ResultSet object that will be returned, It’s an Interface defined inside java.sql. Package.

The ResultSetMetaData object can be obtained by calling the getMetaData() method in the ResultSet object obtained when a SQL query is executed. After getting a OracleResultSetMetaData object, you can use the methods in it to get details about the columns in the ResultSet.All the methods in OracleResultSetMetaData return boolean, int or String.

  • getColumnCount() method returns number of columns in the ResultSet as an int.
  • getColumnName() method returns the column name as a String.
  • getColumnTypeName() method returns the column type as a String.
  • isNullable() method returns if the the column can be NULL. This method returns an int which can be any one of the

following constants:

  • columnNoNulls                – indicates that a column does not allow NULL values
  • columnNullable                – indicates that a column allows NULL values
  • columnNullableUnknown – indicates that the nullability of a column’s values is unknown

OracleResultSetMetaData interface does not implement the getSchemaName() and getTableName() methods because underlying protocol does not make this feasible.

//Get the connection
Connection connection = DriverManager.getConnection
(url, username, password);
//Create a statement object
Statement stmt = connection.createStatement();
// Run the Query
ResultSet rs = stmt.executeQuery("SELECT * FROM mysql_all_table");

// Create a Resulsetmetadata object which will Hold the Table schema information
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
for (int i = 1; i < numColumns + 1; i++) {
String columnName = rsmd.getColumnName(i);
String tableName = rsmd.getTableName(i);
}
}


Thanks
R Vashi

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s