The simple meaning of metadata is
data about data. There are two metadata available in the JDBC API -
ResultSetMetaData and DatabaseMetaData.
This interface provide method to
find out information such as number of columns return in the result set , name
and types of column their source table etc.
getMetaData() method of ResultSet
Interface is used to obtained the reference of ResultSetMetaData.
Methods
of ResultSetMetaData:
getColumnCount():Returns the
number of columns in this ResultSet object.
public int getColumnCount()
throws SQLException
getColumnName():Get the
designated column's name.
public String getColumnName(int
column) throws SQLException
getColumnType():Retrieves the
designated column's SQL type
public int getColumnType(int
column) throws SQLException
getTableName():Gets the
designated column's table name.
public String getTableName(int
column) throws SQLException
getColumnTypeName():Retrieves the
designated column's database-specific type name.
public String
getColumnTypeName(int column) throws SQLException
Simple Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import
java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Navindra Jha
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/stu","root","");
Statement
stmt=con.createStatement();
ResultSet
rset=stmt.executeQuery("select * from student");
ResultSetMetaData
rmdata=rset.getMetaData();
System.out.println("Table :
"+rmdata.getTableName(1)+" Database:
"+rmdata.getCatalogName(1));
System.out.println("Column_Name:
Column_Type");
for(int
i=1;i<=rmdata.getColumnCount();i++){
System.out.println(rmdata.getColumnName(i)+": "+rmdata.getColumnTypeName(i));
}
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE,
null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Output:
Table : student Database: stu
Column_Name: Column_Type
name: VARCHAR
roll: INT
marks: INT
No comments:
Post a Comment