2015-02-21 18:10

[轉載] Get Tables And Columns Details In Schema Using JDBC

轉載自:JavaRoots: Get Tables And Columns Details In Schema Using JDBC

This is a sample program written using java and JDBC API , to print all the tables in a database schema . It also prints columns available in the particular table.

  1. package com.datamigration.main; 
  2.  
  3. import java.sql.Connection; 
  4. import java.sql.DatabaseMetaData; 
  5. import java.sql.ResultSet; 
  6. import java.sql.SQLException; 
  7.  
  8. import com.datamigration.db.DataBase; 
  9.  
  10. /** 
  11. * @author Abhishek Somani 
  12. */ 
  13. public class PrintTable { 
  14.  
  15.    public static String SCHEMA_NAME = "${YOUR_SCHEMA_NAME}"; 
  16.  
  17.    public static void main(String[] args) { 
  18.  
  19.        // create and setup your database and get db connection 
  20.        DataBase db = new DataBase(); 
  21.        db.init(); 
  22.  
  23.        try { 
  24.            Connection con = db.getConnection(); 
  25.            DatabaseMetaData metaData = con.getMetaData(); 
  26.  
  27.            String tableType[] = { "TABLE" }; 
  28.  
  29.            StringBuilder builder = new StringBuilder(); 
  30.  
  31.            ResultSet result = metaData.getTables( 
  32.                null, SCHEMA_NAME, null, tableType 
  33.            ); 
  34.  
  35.            while (result.next()) { 
  36.                String tableName = result.getString(3); 
  37.  
  38.                builder.append(tableName + "( "); 
  39.                ResultSet columns = metaData.getColumns( 
  40.                    null, null, tableName, null 
  41.                ); 
  42.  
  43.                while (columns.next()) { 
  44.                    String columnName = columns.getString(4); 
  45.                    builder.append(columnName); 
  46.                    builder.append(","); 
  47.                } 
  48.                builder.deleteCharAt(builder.lastIndexOf(",")); 
  49.                builder.append(" )"); 
  50.                builder.append("\n"); 
  51.                builder.append("----------------"); 
  52.                builder.append("\n"); 
  53.  
  54.            } 
  55.  
  56.            System.out.println(builder.toString()); 
  57.  
  58.        } catch (SQLException e) { 
  59.            // TODO Auto-generated catch block 
  60.            e.printStackTrace(); 
  61.        } 
  62.    } 
  63. } 

This program will print tables along with colmuns like this :
  1. TABLE1( ID,NAME,STATUS,CREATED_AT,UPDATED_AT) 
  2. ----------------------------------- 
  3. TABLE2( ID,NAME,STATUS,CREATED_AT,UPDATED_AT) 

0 回應: