查询mysql数据表 获得表详细信息

public static void main(String[] args) throws Exception {

        Connection connection = DBConnectionUtil.getConnection();
        BaseDao baseDao = new BaseDao(connection);

        String DBName = "fwdb";

        ResultSet resultSet1 = baseDao.getRes("select TABLE_NAME from TABLES where TABLE_SCHEMA = '"+DBName+"'");

        //遍历该数据的所有表
        while (resultSet1.next()) {
            String table_name = resultSet1.getString(1);

            //获得该表的详细信息
            List infos = getColumnInfo(baseDao,table_name);
            int i=0;

            System.out.println("===============================");
            //遍历表的详细信息
            for (TableInfo table : infos) {
                if(i==0){
                    System.out.println("表名称: " + table.getTableName());
                    i++;
                }
                System.out.println(
                        "   " + table.getColumnName()
                        + "  " + table.getDataType() 
                        + "  " + table.getCharacterMaximumLength()
                        + "  " + table.getColumnComment());

            }
            System.out.println("===============================");

        }

        //关闭连接
        baseDao.closeAll(resultSet1, null, connection);
    }
/**
 * 
 * @param baseDao
 * @param tableName
 * @return 获得给表的详细信息
 * @throws Exception
 */
private static List<TableInfo> getColumnInfo(BaseDao baseDao,String tableName) throws Exception {

        ResultSet resultSet = baseDao
                .getRes("select ABLE_NAME,COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,COLUMN_TYPE,COLUMN_COMMENT from COLUMNS where TABLE_NAME = '" + tableName + "'");
        List<TableInfo> tableInfos = new ArrayList<TableInfo>();
        // 获得给表的详细信息添加到 List中
        while (resultSet.next()) {
            TableInfo table = new TableInfo();

            String columnName = resultSet.getString(2);
            String dataType = resultSet.getString(3);
            String characterMaximumLength = resultSet.getString(4);
            String columnComment = resultSet.getString(6);

            table.setTableName(tableName);
            table.setColumnName(columnName);
            table.setDataType(dataType);
            table.setCharacterMaximumLength(characterMaximumLength);
            table.setColumnComment(columnComment);

            tableInfos.add(table);
        }
        return tableInfos;
    }

你可能感兴趣的:(Mysql)