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:com.iver.utiles.connections.ConnectionDB.java

/**
 * Returns the names of the tables/*from w w w. ja  v a  2s.  co m*/
 * 
 * @param conn
 *            Connection
 * 
 * @return Array of string with the names of the tables.
 * 
 * @throws ConnectionException
 */
public String[] getTableNames(Connection conn) throws ConnectionException {
    // Connection conn=getConnectionByName(name);
    ArrayList tableNames = new ArrayList();
    String nombreTablas = "%"; // Listamos todas las tablas
    String[] tipos = new String[1]; // Listamos slo tablas
    tipos[0] = "TABLE";

    try {
        DatabaseMetaData dbmd = conn.getMetaData();
        ResultSet tablas = dbmd.getTables(null, null, nombreTablas, tipos);

        boolean seguir = tablas.next();

        while (seguir) {
            // Mostramos slo el nombre de las tablas, guardado
            // en la columna "TABLE_NAME"
            System.out.println(tablas.getString(tablas.findColumn("TABLE_NAME")));
            tableNames.add(tablas.getString(tablas.findColumn("TABLE_NAME")));
            seguir = tablas.next();
        }
    } catch (SQLException e) {
        throw new ConnectionException(JDBCManager.getTranslation("fallo_obtener_tablas"), e);
    }

    return (String[]) tableNames.toArray(new String[0]);
}

From source file:com.atlassian.jira.startup.JiraSystemInfo.java

/**
 * Obtains database configuration information.  This should be called after the database has been checked for sanity
 * and hence we can safely do some entityengine.xml and database connection test. But this is before the database is
 * auto-created and hence the support team can get valuable configuration information before a real DB cockup is
 * encountered./* w ww  .  j a  v a  2  s.c  o  m*/
 */
public void obtainDatabaseConfigurationInfo() {
    logMsg.outputHeader("Database Configuration");
    final URL entityEngineURL = ClassLoaderUtils.getResource("entityengine.xml", getClass());
    logMsg.outputProperty("Loading entityengine.xml from", entityEngineURL.toString());

    final DatasourceInfo datasourceInfo = connectionFactory.getDatasourceInfo();
    if (datasourceInfo != null) {
        logMsg.outputProperty("Entity model field type name", datasourceInfo.getFieldTypeName());
        logMsg.outputProperty("Entity model schema name", datasourceInfo.getSchemaName());
    }

    Connection connection = null;
    try {
        connection = connectionFactory.getConnection();
        final DatabaseMetaData metaData = connection.getMetaData();
        final SystemInfoUtils jiraSysInfo = new SystemInfoUtilsImpl();

        logMsg.outputProperty("Database Version",
                metaData.getDatabaseProductName() + " - " + metaData.getDatabaseProductVersion());
        logMsg.outputProperty("Database Driver",
                metaData.getDriverName() + " - " + metaData.getDriverVersion());
        logMsg.outputProperty("Database URL", maskURL(metaData.getURL()));
        logMsg.outputProperty(jiraSysInfo.getDbDescriptorLabel(), jiraSysInfo.getDbDescriptorValue());
    } catch (final SQLException e) {
        // dont worry about this exception here. Code later one will barf on the same problem and do more appropriate actions.
        // We are just trying to get startup information for support purposes for now.
        log.debug(e);
    } finally {
        silentlyClose(connection);
    }

}

From source file:com.eryansky.core.db.DbUtilsDao.java

/**
 * ???? Microsoft SQL Server / Oracle ....
 * @return//from   ww w. j  a v a 2 s .  c  om
 * @throws com.eryansky.common.exception.DaoException
 */
protected String getDatabaseProductName() throws DaoException {
    try {
        Connection conn = this.dataSource.getConnection();
        return conn.getMetaData().getDatabaseProductName();
    } catch (SQLException ex) {
        throw new DaoException(ex);
    }
}

From source file:fr.cnes.sitools.datasource.jdbc.business.SitoolsSQLDataSource.java

/**
 * Return the list of tables in the database
 * /*from  ww w .  j a v  a 2s  .c  o m*/
 * @param schemaPattern
 *          the schema pattern to access tables
 * @return the list of table names
 */
public List<Table> getTables(String schemaPattern) {
    String schema = (schemaPattern == null) ? schemaOnConnection : schemaPattern;

    // Oracle : pour supprimer le caractre vide dans chaine
    if (null == schema || schema.equals("")) {
        schema = null;
    }

    ArrayList<Table> tables = new ArrayList<Table>();

    Connection conn = null;
    ResultSet rs = null;
    try {
        conn = getConnection();

        DatabaseMetaData metaData = conn.getMetaData();

        rs = metaData.getTables(null, schema, null, new String[] { "TABLE", "VIEW" });
        while (rs.next()) {
            tables.add(new Table(rs.getString("TABLE_NAME"), rs.getString("TABLE_SCHEM")));
        }
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, null, ex);
    } finally {
        closeConnection(conn);
        closeResultSet(rs);
    }
    return tables;
}

From source file:com.taobao.itest.listener.ITestDataSetListener.java

private void buildDataBaseConfig(TestContext testContext, ITestDataSet annotation,
        List<DatasetConfig> datasetConfigs, String location, String dsName, ReplacementDataSet dataSet)
        throws DatabaseUnitException, SQLException {
    DataSource dataSource = (DataSource) SpringContextManager.getApplicationContext().getBean(dsName);
    Connection connection = DataSourceUtils.getConnection(dataSource);

    // build databaseTester start
    IDatabaseConnection Iconn = getDatabaseConnection(dataSource, connection);
    DatabaseConfig config = Iconn.getConfig();

    String dbType = connection.getMetaData().getDatabaseProductName();
    if ("MySQL".equalsIgnoreCase(dbType)) {
        config.setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, new MySqlMetadataHandler());
    } else if ("Oracle".equalsIgnoreCase(dbType)) {
        config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new Oracle10DataTypeFactory());
    }/*  w  w w.j  a  v a 2s .  c om*/

    Date dbNow = getDbCurrentTime(connection, dbType);
    addSysdateReplacement(dataSet, dbNow);
    addTimeStampReplacement(dataSet, dbNow);

    IDatabaseTester databaseTester = new DefaultDatabaseTester(Iconn);
    databaseTester.setDataSet(dataSet);
    String setUp = annotation.setupOperation();
    DatabaseOperation setUpOperation = "REFRESH".equals(setUp) ? new RefreshOperation()
            : (DatabaseOperation) databaseOperations.asObject(setUp);
    databaseTester.setSetUpOperation(setUpOperation);

    String teardown = annotation.teardownOperation();
    DatabaseOperation teardownOperation = "DELETE".equals(teardown) ? new DeleteOperation()
            : (DatabaseOperation) databaseOperations.asObject(teardown);
    databaseTester.setTearDownOperation(teardownOperation);
    // build databaseTester end

    boolean transactional = DataSourceUtils.isConnectionTransactional(connection, dataSource);
    DatasetConfig datasetConfig = new DatasetConfig(databaseTester, transactional).location(location)
            .dsName(dsName).setupOperation(annotation.setupOperation())
            .teardownOperation(annotation.teardownOperation());

    datasetConfigs.add(datasetConfig);
}

From source file:eu.databata.Propagator.java

private void logPropagatorProperties() {
    LOG.info("\n\n====================== PROPAGATOR PROPERTIES =================== ");
    LOG.info("Propagator enabled:          " + !isPropagatorDisabled());
    LOG.info("Simulation mode:             " + simulationMode);
    LOG.info("Test data used:              " + useTestData);
    LOG.info("Autotransformations enabled: " + enableAutomaticTransformation);
    LOG.info("Database name:               " + databaseName);
    LOG.info("Database code:               " + sqlExecutor.getDatabaseCode());
    LOG.info("Module name:                 " + moduleName);
    LOG.info("Lock table:                  " + lockTable);
    LOG.info("Change history table:        " + changeHistoryTable);
    LOG.info("Propagation objects table:   " + propagationObjectsTable);
    LOG.info("Environment code:            " + environmentCode);
    LOG.info("Environament SQL:            " + environmentSql);
    LOG.info("Revalidation statement:      " + revalidationStatement);
    LOG.info("Module version:              " + (versionProvider != null ? versionProvider.getVersion() : ""));
    Connection connection = null;
    try {/* w  ww  .j a va2 s  .  co m*/
        if (!simulationMode) {
            connection = jdbcTemplate.getDataSource().getConnection();
            LOG.info("User name:                   " + connection.getMetaData().getUserName());
        }
    } catch (SQLException e) {
        LOG.info("Connection info is not accessible");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOG.debug("Closing connection failed.");
            }
        }
    }
    LOG.info("\n=================================================================\n");
    // LOG.info("Revalidation statement : " + propagator.getJdbcTemplate().getDataSource().getConnection().get);
}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

/**
 * List tables from database//from   w w  w. j  a  va 2s .  c o  m
 */
private List<String> listTables(Session session) {
    final List<String> tables = new ArrayList<String>();
    final String[] tableTypes = { "TABLE" };
    final String[] tablePatterns = new String[] { "JBPM_%", "OKM_%", "DEFAULT_%", "VERSION_%", "jbpm_%",
            "okm_%", "default_%", "version_%" };

    session.doWork(new Work() {
        @Override
        public void execute(Connection con) throws SQLException {
            DatabaseMetaData md = con.getMetaData();

            for (String table : tablePatterns) {
                ResultSet rs = md.getTables(null, null, table, tableTypes);

                while (rs.next()) {
                    tables.add(rs.getString(3));
                }

                rs.close();
            }
        }
    });

    return tables;
}

From source file:fr.cnes.sitools.datasource.jdbc.business.SitoolsDataSource.java

/**
 * Get the list of columns of a table//from w  w w  .  j a v  a2 s  .c  om
 * 
 * @param table
 *          Table name
 * @return name of related columns of the table TODO evolution return List<Column>
 */
public List<String> getMetadata(Structure table) {
    List<String> columnNameList = null;
    Connection conn = null;
    ResultSet rs = null;
    try {
        conn = getConnection();

        columnNameList = new ArrayList<String>();
        DatabaseMetaData metaData = conn.getMetaData();
        rs = metaData.getColumns(null, null, Wrapper.getReference(table), null);
        while (rs.next()) {
            columnNameList.add(rs.getString("COLUMN_NAME"));
        }
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, null, ex);
    } finally {
        closeConnection(conn);
        closeResultSet(rs);
    }
    return columnNameList;
}

From source file:fr.cnes.sitools.datasource.jdbc.business.SitoolsDataSource.java

/**
 * Return the list of tables in the database
 * // w ww  . j a  v a2s  . c  o  m
 * @return the list of table names
 * @deprecated use getTables(String schemaPattern) instead
 */
@Deprecated
public List<String> getMetadata() {
    if (tableNameList != null) {
        return tableNameList;
    }
    Connection conn = null;
    ResultSet rs = null;
    try {
        conn = getConnection();

        tableNameList = new ArrayList<String>();
        DatabaseMetaData metaData = conn.getMetaData();
        rs = metaData.getTables(null, schemaOnConnection, null, new String[] { "TABLE" });
        while (rs.next()) {
            tableNameList.add(rs.getString("TABLE_NAME"));
        }
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, null, ex);
    } finally {
        closeConnection(conn);
        closeResultSet(rs);
    }
    return tableNameList;
}

From source file:com.kylinolap.rest.service.QueryService.java

protected List<TableMeta> getMetadata(CubeManager cubeMgr, String project, boolean cubedOnly)
        throws SQLException {

    Connection conn = null;
    ResultSet columnMeta = null;//from   www.  j  a  v  a2s. c  o m
    List<TableMeta> tableMetas = null;

    try {
        DataSource dataSource = getOLAPDataSource(project);
        conn = dataSource.getConnection();
        DatabaseMetaData metaData = conn.getMetaData();

        logger.debug("getting table metas");
        ResultSet JDBCTableMeta = metaData.getTables(null, null, null, null);

        tableMetas = new LinkedList<TableMeta>();
        Map<String, TableMeta> tableMap = new HashMap<String, TableMeta>();
        while (JDBCTableMeta.next()) {
            String catalogName = JDBCTableMeta.getString(1);
            String schemaName = JDBCTableMeta.getString(2);

            // Not every JDBC data provider offers full 10 columns, for
            // example,
            // PostgreSQL has only 5
            TableMeta tblMeta = new TableMeta(catalogName == null ? Constant.FakeCatalogName : catalogName,
                    schemaName == null ? Constant.FakeSchemaName : schemaName, JDBCTableMeta.getString(3),
                    JDBCTableMeta.getString(4), JDBCTableMeta.getString(5), null, null, null, null, null);

            if (!cubedOnly || getProjectManager().isExposedTable(project, tblMeta.getTABLE_NAME())) {
                tableMetas.add(tblMeta);
                tableMap.put(tblMeta.getTABLE_SCHEM() + "#" + tblMeta.getTABLE_NAME(), tblMeta);
            }
        }

        logger.debug("getting column metas");
        columnMeta = metaData.getColumns(null, null, null, null);

        while (columnMeta.next()) {
            String catalogName = columnMeta.getString(1);
            String schemaName = columnMeta.getString(2);

            // kylin(optiq) is not strictly following JDBC specification
            ColumnMeta colmnMeta = new ColumnMeta(catalogName == null ? Constant.FakeCatalogName : catalogName,
                    schemaName == null ? Constant.FakeSchemaName : schemaName, columnMeta.getString(3),
                    columnMeta.getString(4), columnMeta.getInt(5), columnMeta.getString(6),
                    columnMeta.getInt(7), getInt(columnMeta.getString(8)), columnMeta.getInt(9),
                    columnMeta.getInt(10), columnMeta.getInt(11), columnMeta.getString(12),
                    columnMeta.getString(13), getInt(columnMeta.getString(14)),
                    getInt(columnMeta.getString(15)), columnMeta.getInt(16), columnMeta.getInt(17),
                    columnMeta.getString(18), columnMeta.getString(19), columnMeta.getString(20),
                    columnMeta.getString(21), getShort(columnMeta.getString(22)), columnMeta.getString(23));

            if (!cubedOnly || getProjectManager().isExposedColumn(project, colmnMeta.getTABLE_NAME(),
                    colmnMeta.getCOLUMN_NAME())) {
                tableMap.get(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME()).addColumn(colmnMeta);
            }
        }
        logger.debug("done column metas");
    } finally {
        close(columnMeta, null, conn);
    }

    return tableMetas;
}