首页 > 代码库 > Mysql遍历数据库所有表、表名、表列名

Mysql遍历数据库所有表、表名、表列名

java获取数据库的列名、类型等信息 - 岁月淡忘了谁 - 博客园  http://www.cnblogs.com/henuyuxiang/p/6155935.html

    private List<String> getDBTableName() throws Exception {
        List<String> tables = new ArrayList<>();
        String sql = "show tables";
        PreparedStatement pstmt = new DbUtil().getConn().prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()) {
            tables.add(rs.getString(1));
        }
        return tables;
    }
    
    private Map<String, Map<String, String>> getTableColumnName(String tableName) throws Exception {
        String sql = "select * from " + tableName;
        PreparedStatement pstmt = new DbUtil().getConn().prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        ResultSetMetaData rsmd = pstmt.getMetaData();
        Map<String, String> tableColumnName_ClassName = new HashMap<>();
        for (int i = 0; i < rsmd.getColumnCount(); i++) {
            tableColumnName_ClassName.put(rsmd.getColumnName(i+1), rsmd.getColumnClassName(i+1));
        }
        Map<String, Map<String, String>> tableColumnNames = new HashMap<>();
        tableColumnNames.put(tableName, tableColumnName_ClassName);
        return tableColumnNames;
    }
    
    private void getDBAllTablesName_TableColumnsName() throws Exception {
        List<Map> DBAllTablesName_TableColumnsName = new ArrayList<>();
        List<String> tables = this.getDBTableName();
        for (String table : tables) {
            DBAllTablesName_TableColumnsName.add(this.getTableColumnName(table));
        }
        System.out.println(DBAllTablesName_TableColumnsName.toString());
    }

 

Mysql遍历数据库所有表、表名、表列名