WHAT IS JDBC Metadata API?
JDBC’s database metadata API, can be used to get information about tables, views, column names, column types, stored procedures, result sets, and databases. The API would be of need to those who need to write applications that adapt themselves to the specific capabilities of several database systems or to the content of any database.
DatabaseMetaData provides comprehensive information about the database. This interface is implemented by the driver vendors to allow the user to obtain information about the tables of a relational database as a part of JDBC application.
Iterate through a Schema , Get the table Names , Print the Column Names and Column Types for each of the table :
package com.soham.DatabaseMetaDataInfo; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DataBaseMetaDataPOC { public Connection GetJDBCDirectConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); return conn; } public void GetAllAvailableTables(Connection conn) throws SQLException { String eachTableName; Statement stmt=conn.createStatement();; java.sql.ResultSetMetaData rsMetaData; ResultSet rsDBInfo; ResultSet rsTableInfo; /* * DatabaseMetaData provides comprehensive information about the database. * This interface is implemented by the driver vendors to allow the user to * obtain information about the tables of a relational database as a part of * JDBC application. * * JDBC’s database metadata API, can be used to get information about * tables, views, column names, column types, stored procedures, result sets, * and databases. The API would be of need to those who need to write * applications that adapt themselves to the specific capabilities of several * database systems or to the content of any database. */ DatabaseMetaData meta = conn.getMetaData(); //Connection MetaData Information. rsDBInfo = meta.getTables(null, null, null,new String[] {"TABLE"}); //ResultSet of all tables while(rsDBInfo.next()) { eachTableName = rsDBInfo.getString("TABLE_NAME"); System.out.println(" Table Name :: "+eachTableName); if(eachTableName!=null){ rsTableInfo=stmt.executeQuery("Select * from "+eachTableName); rsMetaData=rsTableInfo.getMetaData(); //Table MetaData Information. for(int i=1;i<rsMetaData.getColumnCount()+1;i++) { System.out.println(" Column Name :: "+rsMetaData.getColumnName(i)); System.out.println(" Column Type :: "+rsMetaData.getColumnType(i)); } } } } public static void main(String[] args) { try{ DataBaseMetaDataPOC dbInfoObj=new DataBaseMetaDataPOC(); Connection conObj=dbInfoObj.GetJDBCDirectConnection(); dbInfoObj.GetAllAvailableTables(conObj); }catch (Exception e) { e.printStackTrace(); } } }
No comments:
Post a Comment