如何在JDBC中看到表结构?

时间:2013-10-07 10:35:41

标签: jdbc ojdbc

我是JDBC的新手,我怀疑,如何使用jdbc程序查看表结构..我尝试了代码,但它显示错误我的代码是

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();
      }
   }

}
}

但它显示错误。请帮助任何人如何在jdbc程序中获取表结构,建议我

2 个答案:

答案 0 :(得分:3)

Documentation for ResultSetMetadata

使用ResultSetMetadata

更改您的SQL查询

sql = "desc emp";

作为

sql = "select * from emp";

例如来自文档

 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));

答案 1 :(得分:1)

本机SELECT语句的替代方法可以是DatabaseMetadata.getColumns http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html