AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



java-jdbc: How to retrieve data from a table with unknown structure in java ?

Is there any way to retrieve data from a table, while we have no information about it´s structure? Please explain briefly with source code.

java x 211
jdbc x 32
Posted On : 2013-11-28 22:28:33.0
profile Saksham Kumar - anyforum.in Saksham Kumar
73433936114
up-rate
3
down-rate

Answers


If you have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.

Commonly used methods of ResultSetMetaData interface :
------------------------------------------------------------------------------
  • public int getColumnCount()throws SQLException: it returns the total number of columns in the ResultSet object.
  • public String getColumnName(int index)throws SQLException: it returns the column name of the specified column index.
  • public String getColumnTypeName(int index)throws SQLException: it returns the column type name for the specified index.
  • public String getTableName(int index)throws SQLException: it returns the table name for the specified column index.

How to get the object of ResultSetMetaData:
-------------------------------------------------------------
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData.

Syntax:
---------------
public ResultSetMetaData getMetaData()throws SQLException  

*************************  Example of ResultSetMetaData interface **************************

import java.sql.*;  
class Rsmd{  
public static void main(String args[]){  
try{  
Class.forName("oracle.jdbc.driver.OracleDriver");  
 
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
 
PreparedStatement ps=con.prepareStatement("select * from emp");  
ResultSet rs=ps.executeQuery();  
 
ResultSetMetaData rsmd=rs.getMetaData();  
 
System.out.println("Total columns: "+rsmd.getColumnCount());  
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));  
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));  
 
con.close();  
 
}catch(Exception e){ System.out.println(e);}  
 
}  
}  
================================  Output  ==================================
Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER

Posted On : 2013-11-28 22:43:54
Satisfied : 1 Yes  0 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523188245674
Reply This Thread
up-rate
4
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in