Using JDBC Database Metadata
- Thursday, October 20, 2011, 3:40
- JDBC Oracle, JDBC Tutorial
- Add a comment
The java.sql.DatabaseMetaData is an interface implemented by the JDBC driver provired. The DatabaseMetaData interface encapsulate all the information related to the database and driver. Using this interface, you can get more detail information about database, all the table in the database, catalog name, table type (view, table, system table, synonym ) etc.
Creating DatabaseMetaData Object: A Connection object represents a database connection and also instantiates a DatabaseMetaData object with the getMetaData() method. The DatabaseMetaData object holds information for the database to which the
Connection object is connected. The following code snippet illustrates how to create a DatabaseMetaData object:
Connection con = DriverManager.getConnection(url,userName,password); DatabaseMetaData dmd = conn.getMetaData();
Using DatabaseMetaData Interface: The DatabaseMetaData object has many methods and properties that provide a lot of information about a database. In fact, when getting started with the DatabaseMetaData interface you may find the number of methods overwhelming.
Following is the code to get all the table from given SCHEMA. It uses Data Source Name to established Connection.
import java.sql.*;
public class DatabaseMetaDataDemo{
public static void main(String[] args)
throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:khanDSN",
"scott","tiger");
DatabaseMetaData db=con.getMetaData();
String[] types={"TABLE"};
ResultSet rs=db.getTables(null,"scott",args[0],types);
System.out.print("Catalog\t");
System.out.print("Table_Schema\t");
System.out.print("Table_Name\t");
System.out.print("Remarks\t\t");
System.out.println("Types_Catalog");
System.out.println("-----------------------------------");
while(rs.next())
{
System.out.print(rs.getString(1)+"\t");
System.out.print(rs.getString(2)+"\t\t");
System.out.print(rs.getString(3)+"\t\t");
System.out.print(rs.getString(4)+"\t\t");
System.out.println(rs.getString(5));
}//while
rs.close();
con.close();
}//main
}//class

