Example usage for java.sql Connection getMetaData

List of usage examples for java.sql Connection getMetaData

Introduction

In this page you can find the example usage for java.sql Connection getMetaData.

Prototype

DatabaseMetaData getMetaData() throws SQLException;

Source Link

Document

Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection.

Usage

From source file:jp.co.golorp.emarf.sql.MetaData.java

/**
 * @param cn//  w  ww.  j a  v a  2  s  .c om
 *            DB?
 * @param tableName
 *            ??
 * @return ????
 */
private static List<ColumnInfo> getColumnInfos(final Connection cn, final String tableName) {

    List<ColumnInfo> columnInfos = new ArrayList<ColumnInfo>();

    ResultSet rs = null;
    try {

        // ??
        rs = cn.getMetaData().getColumns(null, null, tableName, null);
        while (rs.next()) {

            // ?
            ColumnInfo col = new ColumnInfo();
            col.setTableCat(getString(rs, "TABLE_CAT"));
            col.setTableSchem(getString(rs, "TABLE_SCHEM"));
            col.setTableName(getString(rs, "TABLE_NAME"));
            col.setColumnName(getString(rs, "COLUMN_NAME"));
            col.setDataType(getInt(rs, "DATA_TYPE"));
            col.setTypeName(getString(rs, "TYPE_NAME"));
            col.setColumnSize(getInt(rs, "COLUMN_SIZE"));
            col.setBufferLength(getInt(rs, "BUFFER_LENGTH"));
            col.setDecimalDigits(getInt(rs, "DECIMAL_DIGITS"));
            col.setNumPrecRadix(getInt(rs, "NUM_PREC_RADIX"));
            col.setNullable(getInt(rs, "NULLABLE"));
            col.setRemarks(getString(rs, "REMARKS"));
            col.setColumnDef(getString(rs, "COLUMN_DEF"));
            col.setSqlDataType(getInt(rs, "SQL_DATA_TYPE"));
            col.setSqlDatetimeSub(getInt(rs, "SQL_DATETIME_SUB"));
            col.setCharOctetLength(getInt(rs, "CHAR_OCTET_LENGTH"));
            col.setOrdinalPosition(getInt(rs, "ORDINAL_POSITION"));
            col.setIsNullable(getString(rs, "IS_NULLABLE"));
            col.setScopeCatalog(getString(rs, "SCOPE_CATALOG"));
            col.setScopeSchema(getString(rs, "SCOPE_SCHEMA"));
            col.setScopeTable(getString(rs, "SCOPE_TABLE"));
            col.setSourceDataType(getShort(rs, "SOURCE_DATA_TYPE"));
            col.setIsAutoincrement(getString(rs, "IS_AUTOINCREMENT"));
            col.setIsGeneratedcolumn(getString(rs, "IS_GENERATEDCOLUMN"));

            // ?????
            col.setPropertyName(StringUtil.toCamelCase(col.getColumnName()));

            // REMARKS ???? USER_COL_COMMENTS ??
            if (col.getRemarks() == null) {
                col.setRemarks(getColumnCommentByUserColComments(cn, tableName, col.getColumnName()));
            }

            // REMARKS????
            if (col.getRemarks() != null) {
                col.setColumnMei(col.getRemarks().split("\t")[0]);
            }

            columnInfos.add(col);
        }

    } catch (SQLException e) {
        throw new SystemError(e);
    } finally {
        DbUtils.closeQuietly(rs);
    }

    return columnInfos;
}

From source file:org.brickhouse.impl.DatabaseImpl.java

protected boolean tableExists(final String name) {
    return jt.execute(new ConnectionCallback<Boolean>() {
        @Override/*from   www  .  ja v a 2 s. co m*/
        public Boolean doInConnection(Connection con) throws SQLException, DataAccessException {
            return con.getMetaData().getTables(null, null, name.toLowerCase(), null).next();
        }
    });
}

From source file:core.plugin.mybatis.PageInterceptor.java

@Override
public Object intercept(Invocation inv) throws Throwable {
    // prepare?Connection
    Connection connection = (Connection) inv.getArgs()[0];
    String dbType = connection.getMetaData().getDatabaseProductName();
    L.debug(dbType);//from  w  w  w.  j a va 2 s  . c o m
    Dialect dialect = null;
    if (StringUtils.equalsIgnoreCase("ORACLE", dbType)) {
        dialect = new OracleDialect();
    } else if (StringUtils.equalsIgnoreCase("H2", dbType)) {
        dialect = new H2Dialect();
    } else {
        throw new AppRuntimeException("A404: Not Support ['" + dbType + "'] Pagination Yet!");
    }

    StatementHandler target = (StatementHandler) inv.getTarget();
    BoundSql boundSql = target.getBoundSql();
    String sql = boundSql.getSql();
    if (StringUtils.isBlank(sql)) {
        return inv.proceed();
    }
    // ?select??
    if (sql.matches(SQL_SELECT_REGEX) && !Pattern.matches(SQL_COUNT_REGEX, sql)) {
        Object obj = FieldUtils.readField(target, "delegate", true);
        // ??? RowBounds 
        RowBounds rowBounds = (RowBounds) FieldUtils.readField(obj, "rowBounds", true);
        // ??SQL
        if (rowBounds != null && rowBounds != RowBounds.DEFAULT) {
            FieldUtils.writeField(boundSql, "sql", dialect.getSqlWithPagination(sql, rowBounds), true);
            // ???(?)
            FieldUtils.writeField(rowBounds, "offset", RowBounds.NO_ROW_OFFSET, true);
            FieldUtils.writeField(rowBounds, "limit", RowBounds.NO_ROW_LIMIT, true);
        }
    }
    return inv.proceed();
}

From source file:org.beangle.ems.dev.hibernate.web.action.EvolutionAction.java

public void setDataSource(DataSource datasource) throws SQLException {
    this.jdbcTemplate = new JdbcTemplate(datasource);
    Connection connection = datasource.getConnection();
    databaseName = connection.getMetaData().getDatabaseProductName().toLowerCase();
    connection.close();/*  w w w . j  a v a  2 s. co  m*/
}

From source file:org.cloudfoundry.identity.uaa.db.TableAndColumnNormalizationTest.java

@Test
public void checkColumns() throws Exception {
    Connection connection = dataSource.getConnection();
    try {// ww w.  jav  a 2  s  .  c o m
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet rs = metaData.getColumns(null, null, null, null);
        int count = 0;
        while (rs.next()) {
            String name = rs.getString("TABLE_NAME");
            String col = rs.getString("COLUMN_NAME");
            logger.info("Checking column [" + name + "." + col + "]");
            if (name != null && DatabaseInformation1_5_3.tableNames.contains(name.toLowerCase())) {
                logger.info("Validating column [" + name + "." + col + "]");
                assertTrue("Column[" + name + "." + col + "] is not lower case.",
                        col.toLowerCase().equals(col));
            }
        }
    } finally {
        try {
            connection.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:org.hsweb.web.mybatis.SpringApplication.java

@Bean
public SqlExecutor sqlExecutor(DataSource dataSource) throws SQLException {
    Connection connection = dataSource.getConnection();
    try {//from w  ww. j a  va2 s  . c o m
        DataSourceHolder.install(dataSource, DatabaseType.fromJdbcUrl(connection.getMetaData().getURL()));
    } finally {
        connection.close();
    }
    return new AbstractJdbcSqlExecutor() {
        @Override
        public Connection getConnection() {
            return DataSourceUtils.getConnection(dataSource);
        }

        @Override
        public void releaseConnection(Connection connection) throws SQLException {
            DataSourceUtils.releaseConnection(connection, dataSource);
        }
    };
}

From source file:org.cloudfoundry.identity.uaa.db.TableAndColumnNormalizationTest.java

@Test
public void checkTables() throws Exception {
    Connection connection = dataSource.getConnection();
    try {// ww w.j  av a2  s .  co  m
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet rs = metaData.getTables(null, null, null, new String[] { "TABLE" });
        int count = 0;
        while (rs.next()) {
            String name = rs.getString("TABLE_NAME");
            logger.info("Checking table [" + name + "]");
            if (name != null && DatabaseInformation1_5_3.tableNames.contains(name.toLowerCase())) {
                count++;
                logger.info("Validating table [" + name + "]");
                assertTrue("Table[" + name + "] is not lower case.", name.toLowerCase().equals(name));
            }
        }
        assertEquals("Table count:", DatabaseInformation1_5_3.tableNames.size(), count);

    } finally {
        try {
            connection.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.bstek.bdf2.core.orm.jdbc.dialect.AbstractDialect.java

/**
 * ???//from  w  ww.j a  v a  2s  . co  m
 * @param connection ?
 * @param dbProductName ???
 * @param dbMajorVersion ??
 * @return ?????
 */
public boolean support(Connection connection, String dbProductName, String dbMajorVersion) {
    try {
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String databaseProductName = databaseMetaData.getDatabaseProductName();
        int databaseMajorVersion = databaseMetaData.getDatabaseMajorVersion();
        boolean containsMysql = StringUtils.containsIgnoreCase(databaseProductName, dbProductName);
        if (StringUtils.isNotEmpty(dbMajorVersion)) {
            return containsMysql && Integer.valueOf(dbMajorVersion) == databaseMajorVersion;
        }
        return containsMysql;
    } catch (SQLException e) {
        return false;
    }
}

From source file:com.alibaba.otter.canal.example.db.dialect.AbstractDbDialect.java

public AbstractDbDialect(final JdbcTemplate jdbcTemplate, LobHandler lobHandler) {
    this.jdbcTemplate = jdbcTemplate;
    this.lobHandler = lobHandler;
    // ?transction
    this.transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    // ??// w w w. j av a  2s  .  c o  m
    jdbcTemplate.execute(new ConnectionCallback() {

        public Object doInConnection(Connection c) throws SQLException, DataAccessException {
            DatabaseMetaData meta = c.getMetaData();
            databaseName = meta.getDatabaseProductName();
            databaseMajorVersion = meta.getDatabaseMajorVersion();
            databaseMinorVersion = meta.getDatabaseMinorVersion();

            return null;
        }
    });

    initTables(jdbcTemplate);
}

From source file:com.alibaba.dubbo.governance.status.DatabaseStatusChecker.java

public Status check() {
    boolean ok;// w w  w .  j  a  v  a  2s  .  co  m
    try {
        Connection connection = dataSource.getConnection();
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet resultSet = metaData.getTypeInfo();
            try {
                ok = resultSet.next();
            } finally {
                resultSet.close();
            }
            if (message == null) {
                message = metaData.getURL() + " (" + metaData.getDatabaseProductName() + " "
                        + metaData.getDatabaseProductVersion() + ", "
                        + getIsolation(metaData.getDefaultTransactionIsolation()) + ")";
            }
            if (version == 0) {
                version = metaData.getDatabaseMajorVersion();
            }
        } finally {
            connection.close();
        }
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        ok = false;
    }
    return new Status(!ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message);
}