- java.sql.ResultSetMetaData is an interface.
- java.sql.ResultSetMetaData’s object can be used to get information about the types and properties of the columns in a java.sql.ResultSet object.
- java.sql.ResultSetMetaData extends java.sql.Wrapper.
- ResultSetMetaData important methods -
getColumnCount = To find out total number of columns in table
getColumnName = Display table's column type
getColumnTypeName= Display table's column type
--Before executing java program execute these database scripts >
create table EMPLOYEE(ID number(4),NAME varchar2(22));
insert into EMPLOYEE values(1, 'ankit');
insert into EMPLOYEE values(2, 'rohit');
insert into EMPLOYEE values(3, 'amy');
commit;
--If table already exists then execute the DROP command >
drop table EMPLOYEE;
EMPLOYEE table will look like this >
Full Programs JDBC- How to use ResultSetMetaData
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ResultSetMetaDataTest {
public static void main(String... arg) {
Connection con = null;
PreparedStatement prepStmt = null;
ResultSet rs = null;
try {
// registering Oracle driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// getting connection
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl",
"ankit", "Oracle123");
System.out.println("Connection established successfully!");
prepStmt = con.prepareStatement("select * from EMPLOYEE");
//execute select query
//Obtain ResultSet
rs = prepStmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int totalNumberOfColumnsInTable = rsmd.getColumnCount();
System.out.println("\nTotal number of columns in table = "
+ totalNumberOfColumnsInTable);
System.out.println("\nDisplay table's column name and column type - ");
for(int i=1; i<=totalNumberOfColumnsInTable; i++){
System.out.println( " Column no = "+ i +
", column name = " + rsmd.getColumnName(i) +
", column type = " + rsmd.getColumnTypeName(i));
}
rs.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(rs!=null) rs.close(); //close resultSet
if(prepStmt!=null) prepStmt.close(); //close PreparedStatement
if(con!=null) con.close(); // close connection
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/*OUTPUT
Connection established successfully!
Total number of columns in table = 2
Display table's column name and column type -
Column no = 1, column name = ID, column type = NUMBER
Column no = 2, column name = NAME, column type = VARCHAR2
*/
|
RELATED LINKS>