The simple meaning of metadata is
data about data. There are two metadata available in the JDBC API -
ResultSetMetaData and DatabaseMetaData.
This interface provides method to
find out information about the database product being used, Driver Information,
Operation Supported by Database, Details of Table, Procedures, Sequence etc.
getMetaData() method of
Connection interface is used to obtained the reference of database metadata
object.
Commonly used methods:
getDriverName():Retrieves the
name of this JDBC driver.
public String getDriverName()
throws SQLException
getCatalogs():Retrieves the
catalog names available in this database. The results are ordered by catalog
name.
public ResultSet getCatalogs()
throws SQLException
getTables():Retrieves a
description of the tables available in the given catalog. Only table
descriptions matching the catalog, schema, table name and type criteria are
returned. They are ordered by TABLE_TYPE, TABLE_CAT, TABLE_SCHEM and
TABLE_NAME.
public ResultSet getTables(String
catalog, String schemaPattern, String tableNamePattern, String[] types) throws
SQLException
Simple Example:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
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();
DatabaseMetaData
dbm=con.getMetaData();
System.out.println(dbm.getDriverName());
ResultSet set=dbm.getCatalogs();
System.out.println("Available
catalogs are:");
System.out.println("-----------------");
while(set.next()){
System.out.println(
set.getString(1));
}
System.out.println("----------------");
// Third field of the ResultSet
return by the getTables() methods contain the name of the tables.
ResultSet rrset=dbm.getTables(null,
null, null, new String[]{"TABLE"});
System.out.println("Tables in
stu database");
System.out.println("-----------------");
while(rrset.next()){
System.out.println(rrset.getString(1)+" "+rrset.getString(3));
}
System.out.println("---------------");
} 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:
MySQL-AB JDBC Driver
Available catalogs are:
-----------------
information_schema
mysql
performance_schema
stu
test
----------------
Tables in stu database
-----------------
stu person
stu student
---------------
No comments:
Post a Comment