本文例程下载:https://files.cnblogs.com/files/heyang78/ufo_meta_tableColumns_210928.rar
一般来说先有的表后有的Mapper文件,但也有反过来的,今天我就遇到了,在Mapper.xml能找到表名,也有DB可以执行SQL,表字段及说明却无处可寻,只能自己逆向建立起来。
以前曾经做过一个以MetaData取表字段和注释的程序,今天拿它改写一回,便有了下面的程序:
package ufo; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Set; import java.util.TreeSet; public class TableFieldCounter { //-- 以下为连接Oracle数据库的四大参数 private static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orclhy78"; private static final String USER = "luna"; private static final String PSWD = "1234"; /** * 批量打印表和列名 * @param tableNames */ public void printColumnsIn(String... tableNames) { Connection conn = null; try{ Class.forName(DRIVER); conn = DriverManager.getConnection(URL, USER, PSWD); for(String tableName:tableNames) { if(tableName.trim().length()>0) { Set<String> set=findColumnsIn(tableName,conn); System.out.println(" Table:"+tableName.toUpperCase()); for(String col:set) { System.out.println(" "+col); } } } } catch (Exception e) { System.out.print(e.getMessage()); } finally { try { conn.close(); } catch (SQLException e) { System.out.print("Can't close stmt/conn because of " + e.getMessage()); } } } /** * 得到一张表的字段,按字母序排列 * @param tableName * @param conn * @return * @throws Exception */ private Set<String> findColumnsIn(String tableName,Connection conn) throws Exception{ DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs = dbmd.getColumns(null,"%",tableName.toUpperCase(),"%");// 注意%不该改 Set<String> set=new TreeSet<String>(); while(rs.next()) { set.add(rs.getString("COLUMN_NAME"));// 注意COLUMN_NAME不该改 } return set; } /** * 执行点 * @param args */ public static void main(String[] args) { TableFieldCounter tfc=new TableFieldCounter(); tfc.printColumnsIn("emp","testtb",""); } }
执行结果:
Table:EMP
AGE
ID
NAME
Table:TESTTB
AGE
COL1
COL2
COL3
ID
NAME
SEX
-END-