Example usage for java.sql DatabaseMetaData getTables

List of usage examples for java.sql DatabaseMetaData getTables

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getTables.

Prototype

ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[])
        throws SQLException;

Source Link

Document

Retrieves a description of the tables available in the given catalog.

Usage

From source file:org.wso2.carbon.registry.core.jdbc.dataaccess.JDBCClusterLock.java

public void init(DataAccessManager dataAccessManager, String clusterLockTableStatement)
        throws RegistryException {
    synchronized (lockObject) {
        String clusterLockTable;/*from  w  w  w  . ja v  a 2s.co  m*/
        if (log.isTraceEnabled()) {
            log.trace("Initializing cluster wide database locks");
        }
        if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
            String msg = "Failed to get logs. Invalid data access manager.";
            log.error(msg);
            throw new RegistryException(msg);
        }
        setDataSource(((JDBCDataAccessManager) dataAccessManager).getDataSource());

        if (clusterLockTableStatement != null) {
            clusterLockTable = clusterLockTableStatement;
        } else {
            clusterLockTable = defaultClusterLockTableStatement;
        }

        Connection conn = null;

        try {
            conn = getDataSource().getConnection();

            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet result = metaData.getTables(null, null, DBUtils.getConvertedAutoGeneratedColumnName(
                    metaData.getDatabaseProductName(), "REG_CLUSTER_LOCK"), null);
            boolean lockTableCreated = false;
            try {
                if (result.next()) {
                    if (log.isTraceEnabled()) {
                        log.trace("Cluster lock table is already created in the Registry " + "database.");
                    }
                    lockTableCreated = true;
                }
            } finally {
                if (result != null) {
                    result.close();
                }
            }

            if (!lockTableCreated) {
                PreparedStatement ps1 = conn.prepareStatement(clusterLockTable);
                try {
                    ps1.executeUpdate();
                } finally {
                    if (ps1 != null) {
                        ps1.close();
                    }
                }
            }

            int rowCount = 0;
            PreparedStatement psRowCheck = conn.prepareStatement(LOCK_ROW_CHECK);
            try {
                ResultSet rowCheckResults = psRowCheck.executeQuery();
                try {
                    if (rowCheckResults.next()) {
                        rowCount = rowCheckResults.getInt(1);
                    }
                } finally {
                    if (rowCheckResults != null) {
                        rowCheckResults.close();
                    }
                }
            } finally {
                if (psRowCheck != null) {
                    psRowCheck.close();
                }
            }

            // lock table is not created. let's try to create it. we may fail if another node
            // creates this table concurrently.
            conn.setAutoCommit(false);

            // we can't assume that lock row is created even though the lock table is already
            // created. this is because, lock table can be created from a script.
            if (rowCount == 0) {
                PreparedStatement ps2 = conn.prepareStatement(initRow);
                try {
                    ps2.executeUpdate();
                } finally {
                    if (ps2 != null) {
                        ps2.close();
                    }
                }
            }

            conn.commit();

        } catch (SQLException e) {

            String msg = "Attempt create the cluster lock table is unsuccessful. "
                    + "Examining the reasons to failure. "
                    + "(Ignore the below error log if this Registry instance is " + "running in a cluster).";
            log.error(msg, e);

            boolean clusterLockTableCreated = false;
            if (conn != null) {

                try {
                    DatabaseMetaData metaData = conn.getMetaData();
                    ResultSet result = metaData.getTables(null, null,
                            DBUtils.getConvertedAutoGeneratedColumnName(metaData.getDatabaseProductName(),
                                    "REG_CLUSTER_LOCK"),
                            null);
                    try {
                        if (result.next()) {
                            clusterLockTableCreated = true;
                            if (log.isTraceEnabled()) {
                                log.trace("Cluster lock table is created by another node in "
                                        + "the cluster. Cluster lock table creation is " + "successful.");
                            }
                        }
                    } finally {
                        if (result != null) {
                            result.close();
                        }
                    }
                } catch (SQLException e1) {

                    String msg1 = "Failed to check the existence of the cluster lock table. " + "Caused by: "
                            + e1.getMessage();
                    log.error(msg1, e1);
                }

                if (!clusterLockTableCreated) {

                    String msg1 = "Failed to create the cluster lock table. Cluster lock "
                            + "table is not created by any other node. Caused by: " + e.getMessage();
                    log.fatal(msg1, e);

                    try {
                        conn.rollback();
                    } catch (SQLException e1) {
                        String msg2 = "Failed to rollback the database operation after "
                                + "failing the cluster lock table creation. Caused by: " + e1.getMessage();
                        log.error(msg2, e1);
                    }

                    throw new RegistryException(msg1, e);
                }
            } else {
                String msg1 = "Failed to obtain database connection to create the cluster "
                        + "lock table. Caused by: " + e.getMessage();
                log.error(msg1, e);
                throw new RegistryException(msg1, e);
            }

        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                log.error("Failed to close the database connection. Caused by: " + e.getMessage(), e);
            }
        }

        if (log.isTraceEnabled()) {
            log.trace("Cluster wide database locks initialized successfully.");
        }
    }
}

From source file:org.wso2.carbon.is.migration.MigrationDatabaseCreator.java

/**
 * Execute Migration Script//from  ww w.j a va2  s .c  o m
 *
 * @throws Exception
 */
public void executeIdentityMigrationScript() throws Exception {

    try {
        conn = dataSource.getConnection();
        conn.setAutoCommit(false);
        String databaseType = DatabaseCreator.getDatabaseType(this.conn);
        if ("mysql".equals(databaseType)) {
            ResourceUtil.setMySQLDBName(conn);
        }
        statement = conn.createStatement();
        DatabaseMetaData meta = conn.getMetaData();
        String schema = null;
        if ("oracle".equals(databaseType)) {
            schema = ISMigrationServiceDataHolder.getIdentityOracleUser();
        }
        ResultSet res = meta.getTables(null, schema, "IDN_AUTH_SESSION_STORE", new String[] { "TABLE" });
        if (!res.next()) {
            String dbscriptName = getIdentityDbScriptLocation(databaseType, Constants.VERSION_5_0_0,
                    Constants.VERSION_5_0_0_SP1);
            executeSQLScript(dbscriptName);
        }
        String dbscriptName = getIdentityDbScriptLocation(databaseType, Constants.VERSION_5_0_0_SP1,
                Constants.VERSION_5_1_0);
        executeSQLScript(dbscriptName);
        conn.commit();
        if (log.isTraceEnabled()) {
            log.trace("Migration script executed successfully.");
        }
    } catch (SQLException e) {
        String msg = "Failed to execute the migration script. " + e.getMessage();
        log.fatal(msg, e);
        throw new Exception(msg, e);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            log.error("Failed to close database connection.", e);
        }
    }
}

From source file:org.apache.cayenne.unit.di.server.SchemaBuilder.java

private void dropSchema(DataNode node, DataMap map) throws Exception {

    List<DbEntity> list = dbEntitiesInInsertOrder(node, map);

    try (Connection conn = dataSourceFactory.getSharedDataSource().getConnection();) {

        DatabaseMetaData md = conn.getMetaData();
        List<String> allTables = new ArrayList<String>();

        try (ResultSet tables = md.getTables(null, null, "%", null)) {
            while (tables.next()) {
                // 'toUpperCase' is needed since most databases
                // are case insensitive, and some will convert names to
                // lower
                // case
                // (PostgreSQL)
                String name = tables.getString("TABLE_NAME");
                if (name != null)
                    allTables.add(name.toUpperCase());
            }/*  w  ww.j  a v  a 2s  . co  m*/
        }

        unitDbAdapter.willDropTables(conn, map, allTables);

        // drop all tables in the map
        try (Statement stmt = conn.createStatement();) {

            ListIterator<DbEntity> it = list.listIterator(list.size());
            while (it.hasPrevious()) {
                DbEntity ent = it.previous();
                if (!allTables.contains(ent.getName().toUpperCase())) {
                    continue;
                }

                for (String dropSql : node.getAdapter().dropTableStatements(ent)) {
                    try {
                        logger.info(dropSql);
                        stmt.execute(dropSql);
                    } catch (SQLException sqe) {
                        logger.warn("Can't drop table " + ent.getName() + ", ignoring...", sqe);
                    }
                }
            }
        }

        unitDbAdapter.droppedTables(conn, map);
    }
}

From source file:org.apache.sqoop.connector.jdbc.GenericJdbcExecutor.java

/**
 * Verifies existence of table in the database.
 *
 * @param identifiers Identifiers that are used to build the table's name. Following
 *                    variants are accepted:
 *                    * (catalog, schema, table)
 *                    * (schema, table)/*from   ww  w. ja v  a 2s  . c  om*/
 *                    * (table)
 *                    Return value of any combination is "undefined".
 * @return True if given table exists
 */
public boolean existTable(String... identifiers) {
    int index = 0;
    String catalog = identifiers.length >= 3 ? identifiers[index++] : null;
    String schema = identifiers.length >= 2 ? identifiers[index++] : null;
    String table = identifiers[index];

    try {
        DatabaseMetaData dbmd = connection.getMetaData();
        ResultSet rs = dbmd.getTables(catalog, schema, table, null);

        if (rs.next()) {
            return true;
        } else {
            return false;
        }

    } catch (SQLException e) {
        logSQLException(e);
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0003, e);
    }
}

From source file:gda.jython.scriptcontroller.logging.LoggingScriptController.java

private boolean tableExists() {
    ResultSet rs = null;//from w  w w .java  2 s .  co  m
    try {
        DatabaseMetaData dbmd = conn.getMetaData();

        rs = dbmd.getTables(null, null, tableName.toUpperCase(), new String[] { "TABLE" });
        int rowcount = 0;
        while (rs.next())
            rowcount++;
        rs.close();
        return rowcount != 0;
    } catch (SQLException e) {
        logger.debug("Exception counting number of rows in table by LogginScriptController " + getName(), e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
    }
    return false;
}

From source file:coral.reef.service.ReefCoralDAO.java

public ReefCoralDAO(String dbname, boolean setup, String dbmode, String dbprov, String dbdriver) {

    try {/*from  w  w  w  . j a  va 2  s. c o m*/
        Class.forName(dbdriver);

        String dbconnectstr = "jdbc:" + dbprov + ":" + dbmode + ":" + dbname;
        logger.info("setup/connect to db: " + dbconnectstr);

        conn = DriverManager.getConnection(dbconnectstr, "sa", // username
                "");

        if (!setup) {
            DatabaseMetaData meta = conn.getMetaData();
            ResultSet res = meta.getTables(null, null, "DATAS", new String[] { "TABLE" });
            setup = !res.next();
        }

        if (!setup) {
            DatabaseMetaData meta = conn.getMetaData();
            ResultSet res = meta.getTables(null, null, "STATES", new String[] { "TABLE" });
            setup = !res.next();
        }

        if (dbmode.equals("mem") || setup) {
            logger.info("SETUP DATABASE");

            Statement stat = conn.createStatement();
            // stat.execute("delete from datas;");
            // stat.execute("delete from states;");
            stat.execute("drop table if exists DATAS;");
            stat.execute(
                    "CREATE TABLE DATAS ( id BIGINT, collection VARCHAR(10), name VARCHAR(80), value VARCHAR(1024));");
            stat.execute("CREATE INDEX IDATAS ON DATAS ( id, name );");
            stat.execute("drop table if exists STATES;");
            stat.execute(
                    "CREATE TABLE STATES ( id BIGINT, collection VARCHAR(10), template VARCHAR(80), block INTEGER, round INTEGER, stage INTEGER, msg VARCHAR(1024));");
            stat.execute("COMMIT");

            conn.commit();
            stat.close();
        }

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

From source file:org.talend.core.model.metadata.builder.database.DqRepositoryViewService.java

/**
 * This method is used to connect to database to check if this schema has children.
 * /* w  w  w. j  a v  a 2 s . co  m*/
 * @param dataProvider
 * @param schema
 * @param childrenPattern
 * @param String[] childrenTypes
 * @return boolean
 * @throws Exception
 */
public static boolean isSchemaHasChildren(Connection dataProvider, Schema schema, String childrenPattern,
        String[] childrenTypes) throws Exception {
    TypedReturnCode<java.sql.Connection> rcConn = MetadataConnectionUtils
            .createConnection((DatabaseConnection) dataProvider);
    java.sql.Connection connection = rcConn.getObject();
    DatabaseMetaData dbJDBCMetadata = null;
    ExtractMetaDataUtils extractMeta = ExtractMetaDataUtils.getInstance();
    if (dataProvider instanceof DatabaseConnection) {
        dbJDBCMetadata = extractMeta.getDatabaseMetaData(connection, (DatabaseConnection) dataProvider, false);
    } else {
        TaggedValue taggedValue = TaggedValueHelper.getTaggedValue(TaggedValueHelper.DBTYPE,
                dataProvider.getTaggedValue());
        dbJDBCMetadata = extractMeta.getDatabaseMetaData(connection,
                taggedValue == null ? "default" : taggedValue.getValue());//$NON-NLS-1$
    }
    Package catalogOrSchema = PackageHelper.getCatalogOrSchema(schema);

    Package parentCatalog = PackageHelper.getParentPackage(catalogOrSchema);
    String schemaPattern = catalogOrSchema.getName();
    String catalogName = parentCatalog == null ? null : parentCatalog.getName();

    ResultSet tables = dbJDBCMetadata.getTables(catalogName, schemaPattern, childrenPattern, childrenTypes);
    // MOD msjian TDQ-1806: fixed "Too many connections"
    try {
        if (tables.next()) {
            return true;
        } else {
            return false;
        }
    } finally {
        if (connection != null) {
            ConnectionUtils.closeConnection(connection);
        }
    }
}

From source file:org.geowebcache.diskquota.jdbc.SQLDialect.java

/**
 * Checks if the specified table exists/*from w  ww.j  a  va 2 s . co m*/
 * 
 * @param template
 * @param tableName
 * @return
 */
private boolean tableExists(SimpleJdbcTemplate template, final String schema, final String tableName) {
    try {
        DataSource ds = ((JdbcAccessor) template.getJdbcOperations()).getDataSource();
        return (Boolean) JdbcUtils.extractDatabaseMetaData(ds, new DatabaseMetaDataCallback() {

            public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
                ResultSet rs = null;
                try {
                    rs = dbmd.getTables(null, schema, tableName.toLowerCase(), null);
                    boolean exists = rs.next();
                    rs.close();
                    if (exists) {
                        return true;
                    }
                    rs = dbmd.getTables(null, schema, tableName, null);
                    return rs.next();
                } finally {
                    if (rs != null) {
                        rs.close();
                    }
                }
            }
        });
    } catch (MetaDataAccessException e) {
        return false;
    }
}

From source file:com.l2jfree.sql.L2DataSource.java

/**
 * Obtains <TT>CURRENT_DATABASE</TT> and <TT>CURRENT_SCHEMA</TT> on an arbitrary DBMS.
 * //  www .java  2 s . co  m
 * @throws SQLException if a SQL error occurs
 */
public final void initSQLContext() throws SQLException {
    Connection con = null;

    // remove leftover tables
    try {
        con = getConnection();

        DatabaseMetaData dmd = con.getMetaData();

        final List<String> tables = new ArrayList<String>();
        {
            final ResultSet rs = dmd.getTables(null, null, "_zzz%", BASE_TABLE);
            while (rs.next())
                tables.add(rs.getString(3));
            rs.close();
        }

        int removed = 0;
        final Statement s = con.createStatement();
        for (String table : tables) {
            try {
                s.executeUpdate("DROP TABLE " + table);
                removed++;
            } catch (SQLException e) {
                // table is owned by another user
            }
        }
        s.close();

        if (removed > 0)
            _log.info("Removed " + removed + " temporary tables.");
    } finally {
        L2Database.close(con);
    }

    try {
        con = getConnection();

        // generate a random table name
        final String table = "_zzz" + Rnd.getString(5, Rnd.LOWER_CASE_LETTERS);
        // DO NOT LOOK IT UP NOW

        // attempt to create in current schema instead
        {
            final Statement s = con.createStatement();
            s.executeUpdate("CREATE TABLE " + table + " (x INT)");
            s.close();
        }

        // table did not exist in current schema, we can look it up now
        {
            DatabaseMetaData dmd = con.getMetaData();

            final ResultSet rs = dmd.getTables(null, null, table, BASE_TABLE);
            if (rs.next()) {
                _database = rs.getString(1);
                _schema = rs.getString(2);
            } else
                throw new SQLException("Anomaly/Malfunction."); // should never happen

            if (rs.next())
                throw new SQLException("Please try again later."); // should never happen

            rs.close();
        }

        // remove table
        {
            final Statement s = con.createStatement();
            s.executeUpdate("DROP TABLE " + table);
            s.close();
        }
    } finally {
        L2Database.close(con);
    }
}

From source file:edu.wisc.jmeter.dao.JdbcMonitorDao.java

private void setupTables() {
    final JdbcOperations jdbcOperations = this.jdbcTemplate.getJdbcOperations();

    for (final Map.Entry<String, String> tableConfigEntry : TABLE_CONFIG.entrySet()) {
        jdbcOperations.execute(new ConnectionCallback<Object>() {
            @Override//  w ww.  ja v a 2 s . c om
            public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                final DatabaseMetaData metaData = con.getMetaData();

                final String tableName = tableConfigEntry.getKey();
                final ResultSet tables = metaData.getTables(null, null, tableName, null);
                try {
                    if (!tables.next()) {
                        log.warn("'" + tableName + "' table does not exist, creating.");
                        jdbcOperations.update(tableConfigEntry.getValue());
                    } else {
                        log.info("'" + tableName + "' table already exists, skipping.");
                    }
                } finally {
                    tables.close();
                }

                return null;
            }
        });
    }
}