PreparedStatement ps = connection.prepareStatement(sql); ps.execute(); OracleResultSetMetaData orsmd = (OracleResultSetMetaData) ps.getMetaData(); for(int i=1;i<=orsmd.getColumnCount();i++){ System.out.print("字段名:"+orsmd.getColumnName(i)); System.out.print(" 字段类型:"+orsmd.getColumnTypeName(i)); System.out.print(" 字段长度:"+orsmd.getPrecision(i)); System.out.println(" java类名:"+orsmd.getColumnClassName(i)); }
须要注意的是,得到的orsmd的迭代是从1开始的,而不是习惯上的0。 java
使用oracle提供的jar包的一个好处是它能够经过getColumnClassName()这个方法把数据库字段在java中对应的类型一并得到,省去了后期处理的一个步骤。 mysql
可是,上面这种方法只适用于数据库是oracle的状况,因此下面是更通用的第二种方法: sql
//通用方法 DatabaseMetaData metaData = connection.getMetaData(); ResultSet resultSet = metaData.getColumns(null, null, "tableName", null); while(resultSet.next()){ System.out.print("列名:"+resultSet.getString("COLUMN_NAME")); System.out.print(" 数据类型是:"+resultSet.getString("DATA_TYPE")); System.out.print(" 类型名称是:"+resultSet.getString("TYPE_NAME")); System.out.print(" 列大小是:"+resultSet.getString("COLUMN_SIZE")); System.out.println(" 注释是:"+resultSet.getString("REMARKS")); }
这个方法是从网上搜来的,在数据库是mysql的时候没有任何问题,可是当数据库切换成oracle的时候,返回的resultSet始终是null。在百思不得其解/抓耳挠腮/掀桌子×N以后,终于发现问题出在 getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) 这个方法。这个方法里的第三个参数,也就是表名,它必须是大写...满满的都是怨念,个人oracle明明是/必定是/确定是大小写不敏感... 数据库
在解决上面这个问题后,很快又被第二个跳出来的bug调戏了,这货每次出表结构都要出双份或者三份,也就是同一个字段会返回两到三次.....因而乎.....百思不得其解/抓耳挠腮/掀桌子×N....终于经过google发现下面这一段: oracle
In oracle, Connection.getMetaData() returns meta-data for the entire database, not just the schema you happen to be connected to. So when you supply null as the first two arguments to meta.getColumns(), you're not filtering the results for just your schema. You need to supply the name of the Oracle schema to one of the first two parameters of meta.getColumns(), probably the second one, e.g. meta.getColumns(null, "myuser", "EMPLOYEES", null); It's a bit irritating having to do this, but that's the way the Oracle folks chose to implement their JDBC driver.原来是由于在第二个参数为null的状况下,oracle会返回全部schema下的表的结构...而后,这个schema也就是第二个参数,也必须是大写。。。我在建立用户的时候 明 明用的是小写。。个人oracle明明是/必定是/确定是大小写不敏感...
好吧,大小写的问题留待之后研究,问题先记录之... app