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());
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM