Example usage for java.sql DatabaseMetaData getSchemas

List of usage examples for java.sql DatabaseMetaData getSchemas

Introduction

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

Prototype

ResultSet getSchemas() throws SQLException;

Source Link

Document

Retrieves the schema names available in this database.

Usage

From source file:org.apache.kylin.jdbc.JDBCDriverTest.java

@Test
public void testMetadata1() throws Exception {

    // check the JDBC API here: http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html
    Connection conn = getConnection();

    // test getSchemas();
    List<String> schemaList = Lists.newArrayList();
    DatabaseMetaData dbMetadata = conn.getMetaData();
    ResultSet resultSet = dbMetadata.getSchemas();
    while (resultSet.next()) {
        String schema = resultSet.getString("TABLE_SCHEM");
        String catalog = resultSet.getString("TABLE_CATALOG");

        System.out.println("Get schema: schema=" + schema + ", catalog=" + catalog);
        schemaList.add(schema);//w ww. ja v a 2 s.c  om

    }

    resultSet.close();
    Assert.assertTrue(schemaList.contains("DEFAULT"));
    Assert.assertTrue(schemaList.contains("EDW"));

    // test getCatalogs();
    resultSet = dbMetadata.getCatalogs();

    List<String> catalogList = Lists.newArrayList();
    while (resultSet.next()) {
        String catalog = resultSet.getString("TABLE_CAT");

        System.out.println("Get catalog: catalog=" + catalog);
        catalogList.add(catalog);

    }
    Assert.assertTrue(catalogList.size() > 0 && catalogList.contains("defaultCatalog"));

    /** //Disable the test on getTableTypes() as it is not ready
     resultSet = dbMetadata.getTableTypes();
            
     List<String> tableTypes = Lists.newArrayList();
     while (resultSet.next()) {
     String type = resultSet.getString("TABLE_TYPE");
            
     System.out.println("Get table type: type=" + type);
     tableTypes.add(type);
            
     }
            
     Assert.assertTrue(tableTypes.size() > 0 && tableTypes.contains("TABLE"));
     resultSet.close();
            
     **/
    conn.close();
}

From source file:org.apache.phoenix.query.BaseTest.java

private static void deletePriorSchemas(long ts, String url) throws Exception {
    Properties props = new Properties();
    props.put(QueryServices.QUEUE_SIZE_ATTRIB, Integer.toString(1024));
    if (ts != HConstants.LATEST_TIMESTAMP) {
        props.setProperty(CURRENT_SCN_ATTRIB, Long.toString(ts));
    }//from ww w  . j  a v  a  2  s . c o m
    try (Connection conn = DriverManager.getConnection(url, props)) {
        DatabaseMetaData dbmd = conn.getMetaData();
        ResultSet rs = dbmd.getSchemas();
        while (rs.next()) {
            String schemaName = rs.getString(PhoenixDatabaseMetaData.TABLE_SCHEM);
            if (schemaName.equals(PhoenixDatabaseMetaData.SYSTEM_SCHEMA_NAME)) {
                continue;
            }
            schemaName = SchemaUtil.getEscapedArgument(schemaName);

            String ddl = "DROP SCHEMA " + schemaName;
            conn.createStatement().executeUpdate(ddl);
        }
        rs.close();
    }
    // Make sure all schemas have been dropped
    props.remove(CURRENT_SCN_ATTRIB);
    try (Connection seeLatestConn = DriverManager.getConnection(url, props)) {
        DatabaseMetaData dbmd = seeLatestConn.getMetaData();
        ResultSet rs = dbmd.getSchemas();
        boolean hasSchemas = rs.next();
        if (hasSchemas) {
            String schemaName = rs.getString(PhoenixDatabaseMetaData.TABLE_SCHEM);
            if (schemaName.equals(PhoenixDatabaseMetaData.SYSTEM_SCHEMA_NAME)) {
                hasSchemas = rs.next();
            }
        }
        if (hasSchemas) {
            fail("The following schemas are not dropped that should be:" + getSchemaNames(rs));
        }
    }
}

From source file:org.apache.zeppelin.impala.SqlCompleter.java

private static void getSchemaNames(DatabaseMetaData meta, Set<String> names) throws SQLException {

    try {/*from   w  w  w  .  jav  a  2 s .  com*/
        ResultSet schemas = meta.getSchemas();
        try {
            while (schemas.next()) {
                String schemaName = schemas.getString("TABLE_SCHEM");
                if (!isBlank(schemaName)) {
                    names.add(schemaName + ".");
                }
            }
        } finally {
            schemas.close();
        }
    } catch (Exception e) {
        logger.error("Failed to retrieve the column name", e);
    }
}

From source file:org.apache.zeppelin.jdbc.SqlCompleter.java

/**
 * Return list of schema names within the database
 *
 * @param meta metadata from connection to database
 * @param schemaFilter a schema name pattern; must match the schema name
 *        as it is stored in the database; "" retrieves those without a schema;
 *        <code>null</code> means that the schema name should not be used to narrow
 *        the search; supports '%' and '_' symbols; for example "prod_v_%"
 * @return set of all schema names in the database
 *///from  w  w w  .  j  a v a  2s.  com
private static Set<String> getSchemaNames(DatabaseMetaData meta, String schemaFilter) {
    Set<String> res = new HashSet<>();
    try {
        ResultSet schemas = meta.getSchemas();
        try {
            while (schemas.next()) {
                String schemaName = schemas.getString("TABLE_SCHEM");
                if (schemaFilter.equals("") || schemaFilter == null
                        || schemaName.matches(schemaFilter.replace("_", ".").replace("%", ".*?"))) {
                    res.add(schemaName);
                }
            }
        } finally {
            schemas.close();
        }
    } catch (SQLException t) {
        logger.error("Failed to retrieve the schema names", t);
    }
    return res;
}

From source file:org.apache.zeppelin.mysql.SqlCompleter.java

private static void getSchemaNames(DatabaseMetaData meta, Set<String> names) {

    try {//w ww.  java  2 s  .  c  o  m
        try (ResultSet schemas = meta.getSchemas()) {
            while (schemas.next()) {
                String schemaName = schemas.getString("TABLE_SCHEM");
                if (!isBlank(schemaName)) {
                    names.add(schemaName + ".");
                }
            }
        }
    } catch (Throwable t) {
        logger.error("Failed to retrieve the column name", t);
    }
}

From source file:org.apache.zeppelin.postgresql.SqlCompleter.java

private static void getSchemaNames(DatabaseMetaData meta, Set<String> names) throws SQLException {

    try {/* w ww  .  j  a v  a  2 s.  co m*/
        ResultSet schemas = meta.getSchemas();
        try {
            while (schemas.next()) {
                String schemaName = schemas.getString("TABLE_SCHEM");
                if (!isBlank(schemaName)) {
                    names.add(schemaName + ".");
                }
            }
        } finally {
            schemas.close();
        }
    } catch (Throwable t) {
        logger.error("Failed to retrieve the column name", t);
    }
}

From source file:org.beangle.webapp.database.action.BrowserAction.java

private void loadObjects() throws Exception {
    QueryContext queryConext = getQueryContext();
    DataSource datasource = queryConext.getDataSource();
    DatasourceBean dsbean = queryConext.getDatasourceBean();
    DatabaseMetaData meta = datasource.getConnection().getMetaData();
    List<String> schemas = CollectUtils.newArrayList();
    ResultSet rs = meta.getSchemas();
    while (rs.next()) {
        schemas.add(rs.getString(1));//from   w  w w.j a  v  a2  s  .  com
    }
    //      MetadataLoader loader = new MetadataLoader((Dialect) Class.forName(dsbean.getProvider().getDialect())
    //            .newInstance(), meta);
    Set<Table> tables = CollectUtils.newHashSet();
    if (!schemas.isEmpty()) {
        String schema = get("schema");
        if (StringUtils.isNotEmpty(schema)) {
            queryConext.setSchema(schema);
        }
        if (StringUtils.isEmpty(schema)) {
            schema = queryConext.getSchema();
            if (StringUtils.isEmpty(schema)) {
                schema = schemas.get(0);
            }
        }
        put("schema", schema);
        //         tables = loader.loadTables(null, schema, false);
    }
    put("schemas", schemas);
    put("tables", tables);
}

From source file:org.jumpmind.db.platform.AbstractJdbcDdlReader.java

public List<String> getSchemaNames(final String catalog) {
    JdbcSqlTemplate sqlTemplate = (JdbcSqlTemplate) platform.getSqlTemplate();
    return sqlTemplate.execute(new IConnectionCallback<List<String>>() {
        public List<String> execute(Connection connection) throws SQLException {
            ArrayList<String> schemas = new ArrayList<String>();
            DatabaseMetaData meta = connection.getMetaData();
            ResultSet rs = null;/*from  ww  w.  j  a  va2s  .  co  m*/
            try {

                rs = meta.getSchemas();
                while (rs.next()) {
                    int columnCount = rs.getMetaData().getColumnCount();
                    String schema = rs.getString(1);
                    String schemaCatalog = null;
                    if (columnCount > 1) {
                        schemaCatalog = rs.getString(2);
                    }
                    if ((StringUtils.isBlank(schemaCatalog) || StringUtils.isBlank(catalog))
                            && !schemas.contains(schema)) {
                        schemas.add(schema);
                    } else if (StringUtils.isNotBlank(schemaCatalog) && schemaCatalog.equals(catalog)) {
                        schemas.add(schema);
                    }
                }
                return schemas;
            } finally {
                close(rs);
            }
        }
    });
}

From source file:org.ralasafe.db.DBView.java

public static String[] getAllSchemasFromDB(String dsName) {
    Connection conn = null;/*from www  . j ava  2 s .c om*/
    ResultSet rs = null;

    try {
        conn = DBPower.getConnection(dsName);

        DatabaseMetaData metaData = conn.getMetaData();

        String databaseProductName = DBUtil.getDatabaseProductName(conn);
        if (databaseProductName == DBUtil.MYSQL || databaseProductName == DBUtil.SQLSERVER) {
            rs = metaData.getCatalogs();
        } else {
            rs = metaData.getSchemas();
        }

        List result = new LinkedList();
        while (rs.next()) {
            String name = rs.getString(1);
            result.add(name);
        }

        String[] names = new String[result.size()];
        Iterator itr = result.iterator();
        for (int i = 0; i < names.length; i++) {
            names[i] = (String) itr.next();
        }
        return names;
    } catch (SQLException e) {
        log.error("", e);
        throw new DBLevelException(e);
    } finally {
        DBUtil.close(rs);
        DBUtil.close(conn);
    }
}

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

public static boolean checkSchemaConnection(final String schema, Connection connection,
        boolean notCaseSensitive, String dbType, final StringBuffer retPropsedSchema) throws SQLException {
    ExtractMetaDataUtils extractMeta = ExtractMetaDataUtils.getInstance();
    DatabaseMetaData dbMetaData = extractMeta.getDatabaseMetaData(connection, dbType);
    final StringBuffer proposeSchema = new StringBuffer();
    if (dbMetaData != null) {
        ResultSet rs = dbMetaData.getSchemas();
        while (rs.next()) {
            if (notCaseSensitive) {
                if (rs.getString(1).toLowerCase().compareTo(schema.toLowerCase()) == 0) {
                    extractMeta.setSchema(rs.getString(1));
                    rs.close();/* w ww. jav a2s.  co m*/
                    return (true);
                }
            } else {
                String schemaFromDB = rs.getString(1);
                if (schemaFromDB.toLowerCase().compareTo(schema.toLowerCase()) == 0) {
                    if (schemaFromDB.compareTo(schema) == 0) {
                        extractMeta.setSchema(schema);
                        rs.close();
                        return (true);
                    } else {
                        proposeSchema.append(schemaFromDB);
                    }
                }
            }
        }
        rs.close();
    }
    if (retPropsedSchema != null && 0 < proposeSchema.length()) {
        final StringBuffer userSelectResult = new StringBuffer();
        Display.getDefault().syncExec(new Runnable() {

            public void run() {
                String title = Messages.getString("CheckConnection.CheckSchema.ProposeSchema.title"); //$NON-NLS-1$
                String proposeMessage = Messages.getString("CheckConnection.CheckSchema.ProposeSchema.message", //$NON-NLS-1$
                        new Object[] { schema, proposeSchema });
                MessageDialog messageDialog = new MessageDialog(new Shell(), title, null, proposeMessage,
                        MessageDialog.CONFIRM,
                        new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0);
                if (messageDialog.open() == 0) {
                    retPropsedSchema.append(proposeSchema);
                    userSelectResult.append("true"); //$NON-NLS-1$
                }
            }
        });
        if (0 < userSelectResult.length()) {
            return true;
        }
    }
    return false;
}