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:edu.ncsa.sstde.indexing.postgis.PostgisIndexerSettings.java

private boolean isInitialized(Connection conn) throws SQLException {
    ResultSet tables = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });

    try {// w  w  w  . jav  a 2  s  .c  om
        while (tables.next()) {
            String table = tables.getString(3);
            if (getTableName().equalsIgnoreCase(table)) {
                return true;
            }
        }
        return false;
    } finally {
        tables.close();
    }
}

From source file:adapter.gbase.signalling.SignallingAdapter.java

private boolean tableExist(String tableName) {
    boolean result = false;
    ResultSet resultSet = null;/*w w  w. j a  va  2s .c om*/
    try {
        Connection conn = DbKit.getConfig("gbase").getConnection();
        DatabaseMetaData dma = conn.getMetaData();
        resultSet = dma.getTables(null, null, tableName.toUpperCase(), null);
        boolean more = resultSet.next();
        if (more) {
            result = true;
        }
    } catch (Exception ex) {

    }
    return result;

}

From source file:com.netspective.axiom.connection.BasicConnectionProviderEntry.java

public void init(String dataSourceId, Connection conn) {
    this.dataSourceId = dataSourceId;

    try {//w  ww  .  j  av  a 2 s  .  co m
        try {
            DatabasePolicy policy = DatabasePolicies.getInstance().getDatabasePolicy(conn);
            put(KEYNAME_DATABASE_POLICY_CLASSNAME, policy.getClass().getName());
            put(KEYNAME_DATABASE_POLICY_DBMSID, policy.getDbmsIdentifier());
        } catch (Exception dpe) {
            put(KEYNAME_DATABASE_POLICY_CLASSNAME, dpe.toString());
        }

        DatabaseMetaData dbmd = conn.getMetaData();

        put(KEYNAME_DRIVER_NAME, dbmd.getDriverName());
        put(KEYNAME_DATABASE_PRODUCT_NAME, dbmd.getDatabaseProductName());
        put(KEYNAME_DATABASE_PRODUCT_VERSION, dbmd.getDatabaseProductVersion());
        put(KEYNAME_DRIVER_VERSION, dbmd.getDriverVersion());
        put(KEYNAME_URL, dbmd.getURL());
        put(KEYNAME_USER_NAME, dbmd.getUserName());

        String resultSetType = "unknown";
        if (dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE))
            resultSetType = "scrollable (insensitive)";
        else if (dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE))
            resultSetType = "scrollable (sensitive)";
        else if (dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY))
            resultSetType = "non-scrollabe (forward only)";
        put(KEYNAME_RESULTSET_TYPE, resultSetType);

        valid = true;
    } catch (Exception e) {
        exception = e;
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            log.error("SQL Exception while closing connection", e);
        }
    }
}

From source file:org.apache.syncope.core.util.ImportExport.java

public void export(final OutputStream os) throws SAXException, TransformerConfigurationException {

    StreamResult streamResult = new StreamResult(os);
    final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory
            .newInstance();/*  w  w w  .j a  v a  2 s  .c  o  m*/

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    final Connection conn = DataSourceUtils.getConnection(dataSource);

    ResultSet rs = null;

    try {
        final DatabaseMetaData meta = conn.getMetaData();

        final String schema = readSchema();

        rs = meta.getTables(null, schema, null, new String[] { "TABLE" });

        final Set<String> tableNames = new HashSet<String>();

        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");

            // these tables must be ignored
            if (!tableName.toUpperCase().startsWith("QRTZ_")
                    && !tableName.toUpperCase().startsWith("LOGGING_")) {
                tableNames.add(tableName);
            }
        }

        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(conn, tableNames, schema)) {
            doExportTable(handler, conn, tableName);
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}

From source file:eu.databata.Propagator.java

@Override
public void afterPropertiesSet() throws Exception {
    if (!simulationMode) {
        Validate.notNull(jdbcTemplate);/*from ww  w.  j  a v  a  2 s .c  om*/
    }
    Validate.notNull(moduleName);
    String databaseCode = "ORA";
    if (!simulationMode) {
        Connection connection = jdbcTemplate.getDataSource().getConnection();
        databaseName = connection.getMetaData().getDatabaseProductName();
        connection.close();
        databaseCode = PropagationUtils.getDatabaseCode(databaseName);
    }

    propagationDAO = new PropagationDAO();
    propagationDAO.setJdbcTemplate(jdbcTemplate);
    if (StringUtils.isNotEmpty(changeHistoryTable)) {
        propagationDAO.setChangeHistoryTable(changeHistoryTable);
    }
    if (StringUtils.isNotEmpty(lockTable)) {
        propagationDAO.setLockTable(lockTable);
    }
    if (StringUtils.isNotEmpty(propagationObjectsTable)) {
        propagationDAO.setPropagationObjectsTable(propagationObjectsTable);
    }
    if (StringUtils.isNotEmpty(historyLogTable)) {
        propagationDAO.setHistoryLogTable(historyLogTable);
    }
    propagationDAO.setDatabaseCode(databaseCode);

    propagatorLock = simulationMode ? new DummyPropagatorLock(propagationDAO)
            : new PropagatorLock(propagationDAO);
    SQLExceptionHandler exceptionHandler = SQLExceptionFactory.newHandler(databaseCode);
    historyLogger = new DBHistoryLogger(transactionTemplate, propagationDAO, exceptionHandler, moduleName,
            simulationMode);

    sqlExecutor = new SQLPropagationTool();
    sqlExecutor.setJdbcTemplate(jdbcTemplate);
    sqlExecutor.setDatabaseCode(databaseCode);
    sqlExecutor.setModuleName(moduleName);
    if (enableAutomaticTransformation) {
        sqlExecutor.setTransformer(new StandardTransformer(databaseCode));
    }
    sqlExecutor.setSimulationMode(simulationMode);
    sqlExecutor.setHistoryLogger(historyLogger);
    sqlExecutor.setPropagationDAO(propagationDAO);

    logPropagatorProperties();

    // Prepare supplement files
    packageHeaders = new SupplementPropagation(
            canPropagateHeadersSeparately() ? packagesHeaderDirectory : packagesDirectory,
            ObjectType.PACKAGE_HEADER, moduleName, sqlExecutor, propagationDAO, getPackageHeaderRegexp());
    packageHeaders.setPropagatorFileHandler(getFileHandler());
    packageHeaders.setSimulationMode(simulationMode);
    packageHeaders.setVersionProvider(versionProvider);
    packageHeaders.collectPropagatedFiles();

    functions = new SupplementPropagation(functionsDirectory, ObjectType.FUNCTION, moduleName, sqlExecutor,
            propagationDAO, getFunctionRegexp());
    functions.setPropagatorFileHandler(getFileHandler());
    functions.setSimulationMode(simulationMode);
    functions.setVersionProvider(versionProvider);
    functions.collectPropagatedFiles();

    procedures = new SupplementPropagation(proceduresDirectory, ObjectType.PROCEDURE, moduleName, sqlExecutor,
            propagationDAO, getProcedureRegexp());
    procedures.setPropagatorFileHandler(getFileHandler());
    procedures.setSimulationMode(simulationMode);
    procedures.setVersionProvider(versionProvider);
    procedures.collectPropagatedFiles();

    packages = new SupplementPropagation(packagesDirectory, ObjectType.PACKAGE, moduleName, sqlExecutor,
            propagationDAO, getPackageRegexp());
    packages.setPropagatorFileHandler(getFileHandler());
    packages.setSimulationMode(simulationMode);
    packages.setVersionProvider(versionProvider);
    packages.collectPropagatedFiles();

    views = new ViewPropagation(viewsDirectory, moduleName, sqlExecutor, propagationDAO, getViewRegexp());
    views.setPropagatorFileHandler(getFileHandler());
    views.setSimulationMode(simulationMode);
    views.setVersionProvider(versionProvider);
    views.collectPropagatedFiles();

    triggers = new SupplementPropagation(triggersDirectory, ObjectType.TRIGGER, moduleName, sqlExecutor,
            propagationDAO, getTriggerRegexp());
    triggers.setPropagatorFileHandler(getFileHandler());
    triggers.setSimulationMode(simulationMode);
    triggers.setVersionProvider(versionProvider);
    triggers.collectPropagatedFiles();
}

From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java

public void setDocList(String checkpoint, String str_store_entry) {

    DatabaseMetaData dbm = null;//from   w w  w . j a v a2s . co m
    Connection connection = null;

    logger.log(Level.FINEST, "Setting doclist " + checkpoint);
    logger.log(Level.FINEST, "Setting store_entry " + str_store_entry);
    try {

        connection = ds.getConnection();
        connection.setAutoCommit(true);

        dbm = connection.getMetaData();

        //logger.log(Level.FINE,"Base64 ENCODING...");
        String encode_entry = new String(
                org.apache.commons.codec.binary.Base64.encodeBase64(str_store_entry.getBytes()));
        str_store_entry = encode_entry;

        //logger.log(Level.FINE,"Setting store_entry ENCODED " + str_store_entry);

        if (dbm.getDatabaseProductName().equals("MySQL")) {
            //get the most recent row
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            String update_stmt = "select crawl_set from " + this.instance_table
                    + " where crawl_set=(select max(crawl_set) from " + this.instance_table + ")";
            logger.log(Level.FINE, "Getting lastentryp in db: " + update_stmt);
            ResultSet rs = statement.executeQuery(update_stmt);

            boolean ret_rows = rs.first();

            String last_entry_in_db = null;

            while (ret_rows) {
                BigDecimal crawl_set = rs.getBigDecimal("crawl_set");
                last_entry_in_db = crawl_set.toPlainString();
                ret_rows = rs.next();
            }

            logger.log(Level.FINER, "Last_Entry_in_Database " + last_entry_in_db);

            if (last_entry_in_db != null) {
                if (last_entry_in_db.startsWith(checkpoint)) {
                    //increment if in the same set
                    BigDecimal bd = new BigDecimal(last_entry_in_db);
                    bd = bd.add(new BigDecimal(".00001"));
                    logger.log(Level.INFO, "Adding to DBStore. Index Value: " + bd.toPlainString());
                    update_stmt = "insert into " + this.instance_table
                            + " (crawl_set,crawl_data) values (?,COMPRESS(?))";

                    PreparedStatement ps = connection.prepareStatement(update_stmt);
                    ps.setString(1, bd.toPlainString());
                    ps.setString(2, str_store_entry);
                    ps.executeUpdate();
                    ps.close();
                } else {
                    //otherwise add the the 0th row for this set
                    logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000");
                    update_stmt = "insert into " + this.instance_table
                            + " (crawl_set,crawl_data) values (?,COMPRESS(?))";
                    PreparedStatement ps = connection.prepareStatement(update_stmt);
                    ps.setString(1, checkpoint + ".00000");
                    ps.setString(2, str_store_entry);
                    ps.executeUpdate();
                    ps.close();
                }
            } else {
                logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000");
                update_stmt = "insert into " + this.instance_table
                        + " (crawl_set,crawl_data) values (?,COMPRESS(?))";
                PreparedStatement ps = connection.prepareStatement(update_stmt);
                ps.setString(1, checkpoint + ".00000");
                ps.setString(2, str_store_entry);
                ps.executeUpdate();
                ps.close();

            }

            rs.close();
            statement.close();
            connection.close();
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception initializing context Datasource " + ex);
        return;
    }
}

From source file:com.flexive.ejb.beans.configuration.GlobalConfigurationEngineBean.java

/**
 * Get the global configuration table name including the correct schema
 *
 * @param con an open and valid connection to determine the correct storage vendor
 * @return global configuration table name including the escaped schema
 *///from   www  . j  a va  2 s .c  o  m
private String getConfigurationTable(Connection con) {
    try {
        if (StorageManager.getStorageImpl(con.getMetaData().getDatabaseProductName()).requiresConfigSchema()) {
            if (DatabaseConst.getConfigSchema().endsWith("."))
                return DatabaseConst.getConfigSchema() + TBL_CONFIG_GLOBAL;
            else
                return DatabaseConst.getConfigSchema() + "." + TBL_CONFIG_GLOBAL;
        }
    } catch (SQLException e) {
        LOG.warn(e);
    }
    return TBL_CONFIG_GLOBAL;
}

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

/**
 * Retrieves primary keys of a table/*w  w w .ja v a 2  s .  c  o  m*/
 * 
 * @param table
 *          Table object where name and schema are known
 * @return primary keys of the table as a list
 */
public List<String> getPrimaryKey(Structure table) {

    List<String> columnNameList = new ArrayList<String>();
    Connection conn = null;
    ResultSet rs = null;
    try {
        conn = getConnection();

        DatabaseMetaData metaData = conn.getMetaData();
        rs = metaData.getPrimaryKeys(null, table.getSchemaName(), table.getName());
        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
 * /*from w  w w  .  ja v a  2  s  . 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:name.livitski.tools.persista.StorageBootstrap.java

protected void createDatabase() throws ConfigurationException, DatabaseException {
    String dbName = readSetting(DBNameSetting.class);
    String updateUser = readSetting(UpdaterUserNameSetting.class);
    String updatePass = readSetting(UpdaterPasswordSetting.class);
    String readUser = readSetting(ReaderUserNameSetting.class);
    String readPass = readSetting(ReaderPasswordSetting.class);
    String legend = "Creating database " + dbName;
    Connection jdbcAdmin = openDB(null, creatorUser, creatorPass);
    try {/* w  w w .  ja v  a2 s  .  c  o m*/
        String url = jdbcAdmin.getMetaData().getURL();
        legend += " at " + url;
        List<String> script = new ArrayList<String>();
        script.add("CREATE DATABASE " + dbName);
        script.add("GRANT ALTER, CREATE, CREATE TEMPORARY TABLES, CREATE VIEW, DELETE, DROP,"
                + " INDEX, INSERT, LOCK TABLES, REFERENCES, SELECT, SHOW VIEW, UPDATE ON " + dbName + ".* TO '"
                + updateUser + "' IDENTIFIED BY '" + updatePass + "'");
        if (null != readUser) {
            script.add("GRANT SELECT ON " + dbName + ".* TO '" + readUser + "' IDENTIFIED BY '"
                    + (null == readPass ? "" : readPass) + "'");
        }
        ScriptRunner runner = new ScriptRunner(jdbcAdmin, log(), script.toArray(), legend);
        runner.execute();
        creatorPass = null;
    } catch (SQLException fail) {
        throw new DatabaseException(this, "Error " + legend, fail);
    } finally {
        closeDB(jdbcAdmin);
    }
}