日期:2014-05-16  浏览次数:20371 次

mysql来获得数据库的所有表
方法一:使用metadata元数据
	public String[] getTableArray() {
		Connection conn = null;
		ResultSet rs = null;
		ArrayList<String> tbList = new ArrayList<String>();  
		String[] tables = null;
		try {
			conn = connectionUtil.getConnection();
			DatabaseMetaData meta = conn.getMetaData();
			rs = meta.getTables(null,meta.getUserName(),null,new String[]{"TABLE"});
			while(rs.next()){
				tbList.add(rs.getString(3));         
			}
			tables = new String[tbList.size()];
			tbList.toArray(tables);
		} catch (SQLException e) {
			logger.error(e);
		} catch(Exception e){
			logger.error(e);
		} finally {
			try{
				if(null != conn){
					conn.close();
				}
			}catch(Exception e){
				logger.error(e);
			}
		}

		return tables;
	}


方法二:使用命令show tables;缺点:它会把视图也查出来
         private static final String COMMON_SPLIT_STR = ",";
	public String[] getTableArray() {
		String sql = "show tables";
		Connection conn = null;
		Statement sta = null;
		ResultSet rs = null;
		StringBuffer tableNameStr = new StringBuffer();
		try {
			conn = connectionUtil.getConnection();
			sta = conn.createStatement();
			rs = sta.executeQuery(sql);
			while (rs.next()) {
				tableNameStr.append(rs.getString(1)).append(COMMON_SPLIT_STR);
			}
		} catch (SQLException e) {
			logger.error(e);
		} catch(Exception e){
			logger.error(e);
		} finally {
			connectionUtil.closeConnection(conn, sta, rs);
		}

		return tableNameStr.toString().split(COMMON_SPLIT_STR);
	}