获取一个数据库的全部表名,广为人知的应该是通过SQL去查,比方说:
- Oracle数据库获取全部表名的SQL如:select * from user_tables;
- MySQL数据库获取全部表名的SQL如:SHOW TABLES;
- SQLServer数据库获取全部表名的SQL如:SELECT * FROM sysobjects WHERE xtype = 'u';
- DB2数据库获取全部表名的SQL如:SELECT * FROM SYSIBM.TABLES;
但是这里要介绍的是借助DatabaseMetaData.getTable()方法来获取数据库的全部表或视图,
API介绍
/**
* 得到全部表名
* @param String catalog 类别名称;它必须与存储在数据库中的类别名称匹配;该参数为 "" 表示获取没有类别的那些描述;为 null 则表示该类别名称不应该用于缩小搜索范围
* @param String schemaPattern 数据库名,对于oracle来说就用户名
* @param String tableNamePattern 表名称模式;它必须与存储在数据库中的表名称匹配,支持模糊查询,%和_连个占位符,和在数据库中占位符意义一样
* @param String[] types 表的类型(TABLE | VIEW)
* @return 每一行都是一个列描述
* @throws SQLException 如果发生数据库访问错误
*/
ResultSet getTables(String catalog,
String schemaPattern,
String tableNamePattern,
String types[])
throws SQLException
话不多说,附上代码
public static Page pageAllTable(String tableNamePattern, int pageSize, int pageNum) {
List<Map<String, Object>> queryList = new ArrayList<Map<String, Object>>();
Page page = new Page();
Connection conn = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
DatabaseMetaData dbmd = conn.getMetaData();
if(StringUtils.isBlank(tableNamePattern)) {
tableNamePattern = "%";
}else {
tableNamePattern = "%" + tableNamePattern.toUpperCase() + "%";
}
/**
* 参数说明:
* catalog:目录名称,一般都为空
* schema:数据库名,对于oracle来说就用户名
* tableNamePattern:表名称,支持模糊查询,%和_连个占位符,和在数据库中占位符意义一样
* type :表的类型(TABLE | VIEW)
*/
rs = dbmd.getTables(null, "CSBDEVW", tableNamePattern, new String[] {"TABLE", "VIEW"});
List<Map<String, Object>> tempList = new ArrayList<Map<String, Object>>();
while(rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("table_name", rs.getString("table_name"));
map.put("table_type", rs.getString("table_type"));
map.put("remarks", rs.getString("remarks"));
tempList.add(map);
// System.out.println(map);
}
//设置总行数
int totalRows = tempList.size();
page.setTotal(totalRows);
int beginIndex = (pageNum - 1) * pageSize;
int endIndex = pageNum * pageSize;
for (int i = 0; i < tempList.size(); i++) {
if(i >= endIndex) {
break;
}
if(i < beginIndex) {
continue;
}
queryList.add(tempList.get(i));
}
page.setRows(queryList);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (null != conn) {
conn.close();
}
if (null != rs) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return page;
}