2

我是 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 程序中获取表结构,建议我

4

2 回答 2

6

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));
于 2013-10-07T10:37:26.583 回答
2

替代原生 SELECT 语句可以是 DatabaseMetadata.getColumns http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html

于 2013-10-07T11:15:00.977 回答