how to see table structure in JDBC?

user2854207 picture user2854207 · Oct 7, 2013 · Viewed 15.6k times · Source

I'm new to JDBC,i've doubt,how to see the table structure using jdbc program..give code plese i tried but it showing error my code is

import java.sql.*;

public class ram {

   static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";  
   static final String DB_URL = "jdbc:oracle:thin:@192.168.1.12:1521:aftdb";


   static final String USER = "system";
   static final String PASS = "manager";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{

      Class.forName("oracle.jdbc.driver.OracleDriver");


      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);


      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "desc emp";
      ResultSet rs = stmt.executeQuery(sql);

      while(rs.next()){

         String emp= rs.getString("emp");


         System.out.println("ID: " + emp);
      }

      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){

      se.printStackTrace();
   }catch(Exception e){

      e.printStackTrace();
   }finally{

      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }

}
}

but it showing error.please help any one how to get table structure in jdbc program,suggest me

Answer

Naveen Kumar Alone picture Naveen Kumar Alone · Oct 7, 2013

Documentation for ResultSetMetadata

Use ResultSetMetadata

Change your sql query

sql = "desc emp";

as

sql = "select * from emp";

For example from documentation

 ResultSet rs = stmt.executeQuery("select * from emp");
 ResultSetMetaData rsmd = rs.getMetaData();
 System.out.println("No. of columns : " + rsmd.getColumnCount());
 System.out.println("Column name of 1st column : " + rsmd.getColumnName(1));
 System.out.println("Column type of 1st column : " + rsmd.getColumnTypeName(1));