JDBC ResultSet Metadata using Oracle

In the simplest meaning, metadata is data about data.When you apply this to database, metadata is information about database data, or about table data. Examples of metadata are descriptions of the tables and column attributes, column type etc

The JDBC API enables you to uncover metadata about a database and a query’s result set using the DatabaseMetaData and ResultSetMetaData interfaces, respectively. The first interface enables you to obtain information about your database’s attributes and make runtime decisions based around that information. The second interface enables you to determine the attributes — such as number of columns, names, and data types — for a result set.

The ResultSetMetaData Interface: The ResultSetMetaData interface provides descriptive information about the columns in a result set such as the number of columns it contains or each column’s data type. The interface does not provide information regarding the database or the number of rows in the result set.

Creating ResultSetMetaData Object: The ResultSetMetaData object is instantiated from a valid ResultSet object. The following code snippet creates a ResultSetMetaData object, rsmd, that contains the column metadata for the entire Employees table:

Connection con = DriverManager.getConnection(url,userName,password);
Statement stmt = conn.createStatement();
//Create a result set
ResultSet rs = stmt.executeQuery("SELECT * FROM Employees");
//Obtain the result set metadata
ResultSetMetaData rsmd = rs.getMetaData();

Using ResultSetMetaData Interface: The ResultSetMetaData interface provides you with numerous methods for retrieving information about the result set. You call the various setter and getter methods to retrieve data from the ResultSetMetaData object. Following is the example given to know more about ResultSetMetaData.

import java.sql.*;
import java.util.*;
 
public class ResultSetMDDemo {
 
	public static void main(String s[]) throws Exception {
	Driver d =(Driver)Class.forName("oracle.jdbc.driver.OracleDriver")
			.newInstance();
 
	Properties p = new Properties();
	p.put("user", "scott");
	p.put("password", "tiger");
 
	Connection con = d.connect("jdbc:oracle:thin:@mysys:1521:khan",p);
	Statement st = con.createStatement();
	ResultSet rs = st.executeQuery("select * from "+s[0]);
 
	//Table name is taken as an command line arg
	ResultSetMetaData rsmd = rs.getMetaData();
	System.out.println("Table Name : "+s[0]);
	int colcount = rsmd.getColumnCount();
 
	for (int i=1;i<=colcount;i++) {
		System.out.print(rsmd.getColumnName(i)+"\t");
		System.out.println(rsmd.getColumnTypeName(i));
	}//for
 
	con.close();
	}//main
 
}//class

About the Author

has written 22 posts on this blog.

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2013 JDBC Tutorial. All rights reserved.
Proudly powered by WordPress. Developed by 7tech Solutions