package com.hcks.cmfds.commons.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashSet; import java.util.Set; import javax.sql.DataSource; import org.apache.log4j.Logger; import com.hcks.cmfds.core.exception.JdbcDaoException; /** * * * @Author 刘厦 (liusha.information@gmail.com) * @Date 创建时间:2011-7-19,上午10:06:06 * @Version 0.0.0 * * 类说明: * */ public class DataBaseHelper { protected final Logger logger = Logger.getLogger(DataBaseHelper.class); /** * 获取数据库表 * @param dataSource * @return */ public static Set getTablesByDataSource(DataSource dataSource){ Set tables = new HashSet(); ResultSet _result = null; Connection conn = null; try { conn = dataSource.getConnection(); _result = conn.getMetaData().getTables(null, "%", "%", new String[]{"TABLE"}); while (_result.next()) { String tableName = _result.getString("TABLE_NAME"); tables.add(tableName); } } catch (SQLException e) { try { conn.close(); } catch (SQLException e1){ e.printStackTrace(); } throw new JdbcDaoException("获取元数据错误!"); } finally{ _result = null; try { conn.close(); } catch (SQLException e2){ e2.printStackTrace(); } } return tables; } /** * 获取表的主键集合 * @param tableName * @return */ public static Set getTablePrimaryKeyFieldNames(String tableName,DataSource dataSource) { Set pks = new HashSet(); ResultSet _result = null; Connection conn = null; try { conn = dataSource.getConnection(); _result = conn.getMetaData().getPrimaryKeys(null, null, tableName); while (_result.next()) { pks.add(_result.getString(4)); } } catch (SQLException e) { try { conn.close(); } catch (SQLException e1){ e.printStackTrace(); } throw new JdbcDaoException("获取元数据错误!"); } finally{ _result = null; try { conn.close(); } catch (SQLException e2){ e2.printStackTrace(); } } return pks; } /** * 获取表的所有字段 * @param tableName * @return */ public static Set getTableFieldNames(String tableName,DataSource dataSource){ Set columns = new HashSet(); ResultSet _result = null; Connection conn = null; try { conn = dataSource.getConnection(); _result = conn.getMetaData().getColumns(null, "%", tableName, "%"); while (_result.next()) { String columnName = _result.getString("COLUMN_NAME"); columns.add(columnName); } } catch (SQLException e) { try { conn.close(); } catch (SQLException e1){ e.printStackTrace(); } throw new JdbcDaoException("获取元数据错误!"); } finally{ _result = null; try { conn.close(); } catch (SQLException e2){ e2.printStackTrace(); } } return columns; } /** * 判断表是否是单主键 * @param tableName * @return */ public boolean isSinglePk(String tableName,DataSource dataSource){ return getTablePrimaryKeyFieldNames(tableName,dataSource).size() == 1; } }