【JDBC】利用DatabaseMetaData获得表下的所有字段
【核心语句】
DatabaseMetaData metaData = conn.getMetaData(); ResultSet rs= metaData.getColumns(null, null, tablename+"%", null);
重点是第二句的第三参数,如果置空就不分表了,那不是我们想看到的,于是将表名加上通配符%限制一下表的范围,再这样限制表:
while (rs.next()) { String tbName = rs.getString("TABLE_NAME"); // 表名 if(tbName.equalsIgnoreCase(tablename)){ String columnName = rs.getString("COLUMN_NAME"); // 列名 ls.add(columnName); } }
当取得rs的TABLE_NAME字段后,再限制一次,这下出现的字段就只会是指定表下的了。
【代码】
package com.hy.lab; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 此类用于查出某表下的所有字段名称 */ public class FieldFinder { //-- 以下为连接Oracle数据库的四大参数 private static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; private static final String USER = "luna"; private static final String PSWD = "1234"; public void printFields(String tablename){ Connection conn = null; try{ Class.forName(DRIVER); conn = DriverManager.getConnection(URL, USER, PSWD); List<String> ls=getFields(conn,tablename); Collections.sort(ls); ls.stream().forEach(table -> System.out.println(table)); } catch (Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } private List<String> getFields(Connection conn,String tablename) throws Exception{ DatabaseMetaData metaData = conn.getMetaData(); ResultSet rs = metaData.getColumns(null, null, tablename+"%", null); List<String> ls=new ArrayList<>(); while (rs.next()) { String tbName = rs.getString("TABLE_NAME"); // 表名 if(tbName.equalsIgnoreCase(tablename)){ String columnName = rs.getString("COLUMN_NAME"); // 列名 ls.add(columnName); } } return ls; } public static void main(String[] args){ FieldFinder finder=new FieldFinder(); finder.printFields("EMP"); } }
【输出】
COMM
DEPTNO
EMPNO
ENAME
HIREDATE
JOB
MGR
SAL
PS:老外的简写比我们想当然的规范得多。
【参考资料】
https://blog.csdn.net/github_34793283/article/details/114109394
END