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:chh.utils.db.source.common.JdbcClient.java

public List<Column> getColumnSchema(String tableName) {
    Connection connection = null;
    List<Column> columns = new ArrayList<Column>();
    try {/*from   w ww.  j  a  v  a2  s .c  om*/
        connection = connectionProvider.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet resultSet = metaData.getColumns(null, null, tableName, null);
        while (resultSet.next()) {
            columns.add(new Column(resultSet.getString("COLUMN_NAME"), resultSet.getInt("DATA_TYPE")));
        }
        return columns;
    } catch (SQLException e) {
        throw new RuntimeException("Failed to get schema for table " + tableName, e);
    } finally {
        closeConnection(connection);
    }
}

From source file:net.hydromatic.optiq.impl.jdbc.JdbcSchema.java

RelProtoDataType getRelDataType(String catalogName, String schemaName, String tableName) throws SQLException {
    Connection connection = null;
    try {//from   w ww  .j a v a 2s .  com
        connection = dataSource.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        return getRelDataType(metaData, catalogName, schemaName, tableName);
    } finally {
        close(connection, null, null);
    }
}

From source file:com.emr.schemas.ForeignDataMover.java

private List getTableColumns(String tableName, Connection con) {
    List columns = new ArrayList();
    try {/*from  w  ww.j  a  va 2s. c  om*/
        DatabaseMetaData dbmd = con.getMetaData();
        ResultSet rs = dbmd.getColumns(null, null, tableName, "%");
        while (rs.next()) {
            String colName = rs.getString(4);
            columns.add(colName);
        }
    } catch (SQLException e) {
        String stacktrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
        JOptionPane.showMessageDialog(this,
                "Could not fetch Tables for the Database. Error Details: " + stacktrace, "Table Names Error",
                JOptionPane.ERROR_MESSAGE);
    }
    return columns;
}

From source file:com.emr.schemas.ForeignDataMover.java

private List getDatabaseTables(Connection con) {
    List tables = new ArrayList();
    try {/*from ww w . j a v  a2 s .co  m*/

        DatabaseMetaData dbmd = con.getMetaData();
        String[] types = { "TABLE" };
        ResultSet rs = dbmd.getTables(null, null, "%", types);
        while (rs.next()) {
            //Add table name to Jlist
            tables.add(rs.getString("TABLE_NAME"));
        }
    } catch (SQLException e) {
        String stacktrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
        JOptionPane.showMessageDialog(this,
                "Could not fetch Tables for the KenyaEMR Database. Error Details: " + stacktrace,
                "Table Names Error", JOptionPane.ERROR_MESSAGE);
    }
    return tables;
}

From source file:de.walware.statet.r.internal.core.pkgmanager.DB.java

private void checkDB() throws SQLException {
    final Connection connection = getConnection();

    final ResultSet schemas = connection.getMetaData().getSchemas(null, REnv.NAME);
    while (schemas.next()) {
        if (REnv.NAME.equals(schemas.getString(1))) {
            return;
        }/*from   w w  w .  j av  a2 s .com*/
    }

    try (final Statement statement = connection.createStatement()) {
        statement.execute(REnv.LibPaths.DEFINE_1);
        statement.execute(REnv.Pkgs.DEFINE_1);

        connection.commit();
    } catch (final SQLException e) {
        closeOnError();
        throw e;
    }
}

From source file:com.splicemachine.derby.test.framework.SpliceTableWatcher.java

public void start() {
    Statement statement = null;//from  w  w  w  .j  a  va2  s . c o  m
    ResultSet rs;
    Connection connection;
    synchronized (SpliceTableWatcher.class) {
        try {
            connection = (userName == null) ? SpliceNetConnection.getConnection()
                    : SpliceNetConnection.getConnectionAs(userName, password);
            rs = connection.getMetaData().getTables(null, schemaName, tableName, null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    TableDAO tableDAO = new TableDAO(connection);

    try {
        if (rs.next()) {
            tableDAO.drop(schemaName, tableName);
        }
        connection.commit();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

    try {
        statement = connection.createStatement();
        statement.execute(String.format("create table %s.%s %s", schemaName, tableName, createString));
        connection.commit();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
}

From source file:com.predic8.membrane.core.interceptor.statistics.StatisticsJDBCInterceptor.java

private void createTableIfNecessary(Connection con) throws Exception {
    if (JDBCUtil.tableExists(con, JDBCUtil.TABLE_NAME))
        return;//from  www.  j  ava  2s  .c o  m

    Statement st = con.createStatement();
    try {
        if (JDBCUtil.isOracleDatabase(con.getMetaData())) {
            st.execute(JDBCUtil.getCreateTableStatementForOracle());
            st.execute(JDBCUtil.CREATE_SEQUENCE);
            st.execute(JDBCUtil.CREATE_TRIGGER);
        } else if (JDBCUtil.isMySQLDatabase(con.getMetaData())) {
            st.execute(JDBCUtil.getCreateTableStatementForMySQL());
        } else if (JDBCUtil.isDerbyDatabase(con.getMetaData())) {
            st.execute(JDBCUtil.getCreateTableStatementForDerby());
        } else {
            st.execute(JDBCUtil.getCreateTableStatementForOther());
        }
    } finally {
        closeConnection(st);
    }
}

From source file:com.pactera.edg.am.metamanager.extractor.adapter.extract.db.impl.AbstractDBExtractService.java

public final Catalog getCatalog() throws SQLException {
    Connection conn = null;
    try {/*w w  w  .  j  a  v a 2s  .c  o m*/
        conn = jdbcTemplate.getDataSource().getConnection();
        metaData = conn.getMetaData();
    } catch (SQLException e) {
        log.error("DB??SQL!DB????!", e);
        AdapterExtractorContext.addExtractorLog(ExtractorLogLevel.ERROR,
                "DB??SQL!DB????!");
        if (conn != null) {
            conn.close();
        }
        throw e;
    }
    log.info("???!");

    try {
        log.info("??.");

        String catalogName = conn.getCatalog();
        Catalog catalog = new Catalog();
        catalog.setName(catalogName);
        log.info("catalog Name:" + catalogName);
        catalog.setSchemas(internalGetSchemas());

        internalAfterHook(catalog);
        return catalog;
    } catch (SQLException e) {
        log.error("", e);
        AdapterExtractorContext.addExtractorLog(ExtractorLogLevel.ERROR, e.getMessage());
        throw e;
    } finally {
        // ??,???
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:it.greenvulcano.gvesb.j2ee.db.connections.impl.DriverPoolConnectionBuilder.java

public Connection getConnection() throws GVDBException {
    try {//from w ww .  j  a v a  2s .co m
        Connection conn = dataSource.getConnection();
        if (debugJDBCConn) {
            logger.debug("Created JDBC Connection [" + name + "]: [" + conn + "]");
            if (isFirst) {
                isFirst = false;
                DatabaseMetaData dbmd = conn.getMetaData();

                logger.debug("=====  Database info =====");
                logger.debug("DatabaseProductName: " + dbmd.getDatabaseProductName());
                logger.debug("DatabaseProductVersion: " + dbmd.getDatabaseProductVersion());
                logger.debug("DatabaseMajorVersion: " + dbmd.getDatabaseMajorVersion());
                logger.debug("DatabaseMinorVersion: " + dbmd.getDatabaseMinorVersion());
                logger.debug("=====  Driver info =====");
                logger.debug("DriverName: " + dbmd.getDriverName());
                logger.debug("DriverVersion: " + dbmd.getDriverVersion());
                logger.debug("DriverMajorVersion: " + dbmd.getDriverMajorVersion());
                logger.debug("DriverMinorVersion: " + dbmd.getDriverMinorVersion());
                logger.debug("=====  JDBC/DB attributes =====");
                if (dbmd.supportsGetGeneratedKeys())
                    logger.debug("Supports getGeneratedKeys(): true");
                else
                    logger.debug("Supports getGeneratedKeys(): false");
            }
        }

        return conn;
    } catch (Exception exc) {
        throw new GVDBException("DriverPoolConnectionBuilder - Error while creating Connection[" + name + "]",
                exc);
    }
}

From source file:com.uber.hoodie.hive.client.HoodieHiveClient.java

/**
 * Get the table schema//  w ww  .  j av a2 s.  c  o m
 *
 * @param datasetReference
 * @return
 */
public Map<String, String> getTableSchema(HoodieDatasetReference datasetReference) {
    if (!checkTableExists(datasetReference)) {
        throw new IllegalArgumentException(
                "Failed to get schema as table " + datasetReference.getDatabaseTableName() + " does not exist");
    }
    Map<String, String> schema = Maps.newHashMap();
    ResultSet result = null;
    try {
        Connection connection = getConnection();
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        result = databaseMetaData.getColumns(null, datasetReference.getDatabaseName(),
                datasetReference.getTableName(), null);
        while (result.next()) {
            String columnName = result.getString(4);
            String columnType = result.getString(6);
            schema.put(columnName, columnType);
        }
        return schema;
    } catch (SQLException e) {
        throw new HoodieHiveDatasetException("Failed to get table schema for " + datasetReference, e);
    } finally {
        closeQuietly(result, null);
    }
}