Example usage for java.sql DatabaseMetaData getConnection

List of usage examples for java.sql DatabaseMetaData getConnection

Introduction

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

Prototype

Connection getConnection() throws SQLException;

Source Link

Document

Retrieves the connection that produced this metadata object.

Usage

From source file:com.mmnaseri.dragonfly.dialect.impl.Mysql5Dialect.java

@Override
public <E> boolean hasTable(DatabaseMetaData databaseMetadata, TableMetadata<E> tableMetadata) {
    try {//w w  w.ja v a  2  s  .c  o m
        String schema = tableMetadata.getSchema() != null && !tableMetadata.getSchema().isEmpty()
                ? tableMetadata.getSchema()
                : databaseMetadata.getConnection().getCatalog();
        return databaseMetadata.getTables(schema, null, tableMetadata.getName(), new String[] { "TABLE" })
                .next();
    } catch (SQLException e) {
        throw new MetadataCollectionError("Failed to recognize database metadata", e);
    }
}

From source file:org.focusns.service.env.impl.EnvironmentServiceImpl.java

protected Environment lookupDB() {
    try {/*ww  w.j a  v a  2 s .c om*/
        DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
        //
        EnvironmentDB envDB = new EnvironmentDB();
        envDB.setDatabaseName(metaData.getDatabaseProductName());
        envDB.setDatabaseVersion(metaData.getDatabaseProductVersion());
        envDB.setDriverName(metaData.getDriverName());
        envDB.setDriverVersion(metaData.getDriverVersion());
        envDB.setUrl(metaData.getURL());
        envDB.setUsername(metaData.getUserName());
        envDB.setMaxConnections(metaData.getMaxConnections());
        //
        metaData.getConnection().close();
        //
        return envDB;
    } catch (SQLException e) {
        throw new UnsupportedOperationException(e);
    }
}

From source file:jp.co.tis.gsp.tools.dba.s2jdbc.gen.DbTableMetaReaderWithView.java

@Override
protected Set<String> getPrimaryKeySet(DatabaseMetaData metaData, DbTableMeta tableMeta) {
    Set<String> result = new HashSet<String>();
    Dialect gspDialect = DialectUtil.getDialect();
    try {//from w w w  .  j  a  v a  2  s  .  co m
        String typeName = getObjectTypeName(metaData, tableMeta);
        String tableName = tableMeta.getName();
        ViewAnalyzer viewAnalyzer = null;
        if (StringUtils.equals(typeName, "VIEW")) {
            String sql = gspDialect.getViewDefinition(metaData.getConnection(), tableName, tableMeta);
            viewAnalyzer = new ViewAnalyzer();
            viewAnalyzer.parse(sql);
            if (viewAnalyzer.isSimple()) {
                tableName = viewAnalyzer.getTableName().toUpperCase();
            } else {
                return Collections.emptySet();
            }
        }
        ResultSet rs = metaData.getPrimaryKeys(tableMeta.getCatalogName(), tableMeta.getSchemaName(),
                tableName);

        try {
            while (rs.next()) {
                result.add(rs.getString("COLUMN_NAME"));
            }
        } finally {
            ResultSetUtil.close(rs);
        }

        if (viewAnalyzer != null && !result.isEmpty()) {
            Set<String> viewPKs = new TreeSet<String>();
            for (String pkColumn : result) {
                if (viewAnalyzer.getColumnNames().contains(pkColumn.toUpperCase())) {
                    String alias = viewAnalyzer.getAlias((pkColumn.toUpperCase()));
                    viewPKs.add(StringUtils.isEmpty(alias) ? pkColumn : alias);
                }
            }
            System.out.println("View Pks" + viewPKs);
            if (viewPKs.size() == result.size())
                return viewPKs;
            else
                return Collections.emptySet();
        }
        return result;
    } catch (SQLException ex) {
        throw new SQLRuntimeException(ex);
    }
}

From source file:de.erdesignerng.dialect.oracle.OracleReverseEngineeringStrategy.java

@Override
protected void reverseEngineerIndexAttribute(DatabaseMetaData aMetaData, TableEntry aTableEntry, Table aTable,
        ReverseEngineeringNotifier aNotifier, Index aIndex, String aColumnName, short aPosition,
        String aAscOrDesc) throws SQLException, ReverseEngineeringException {

    // This needs only to be checked if it is a function based index
    if (!aColumnName.endsWith("$")) {
        super.reverseEngineerIndexAttribute(aMetaData, aTableEntry, aTable, aNotifier, aIndex, aColumnName,
                aPosition, aAscOrDesc);//ww  w  . ja va 2  s  .  c  o  m
        return;
    }

    Connection theConnection = aMetaData.getConnection();
    PreparedStatement theStatement = theConnection.prepareStatement(
            "SELECT * FROM USER_IND_EXPRESSIONS WHERE INDEX_NAME = ? AND TABLE_NAME = ? AND COLUMN_POSITION = ?");
    theStatement.setString(1, aIndex.getOriginalName());
    theStatement.setString(2, aTable.getOriginalName());
    theStatement.setShort(3, aPosition);
    ResultSet theResult = theStatement.executeQuery();
    boolean found = false;
    while (theResult.next()) {
        found = true;
        String theColumnExpression = theResult.getString("COLUMN_EXPRESSION");

        aIndex.getExpressions().addExpressionFor(theColumnExpression);
    }
    theResult.close();
    theStatement.close();
    if (!found) {
        throw new ReverseEngineeringException("Cannot find index column information for " + aColumnName
                + " index " + aIndex.getName() + " table " + aTable.getName());
    }
}

From source file:jp.co.tis.gsp.tools.dba.s2jdbc.gen.DbTableMetaReaderWithView.java

@Override
protected List<DbForeignKeyMeta> getDbForeignKeyMetaList(DatabaseMetaData metaData, DbTableMeta tableMeta) {
    @SuppressWarnings("unchecked")
    Map<String, DbForeignKeyMeta> map = new ArrayMap();
    Dialect gspDialect = DialectUtil.getDialect();
    try {//from  ww w  .  ja  v a 2  s .co  m
        String typeName = getObjectTypeName(metaData, tableMeta);
        String tableName = tableMeta.getName();
        ViewAnalyzer viewAnalyzer = null;
        if (StringUtils.equals(typeName, "VIEW")) {
            String sql = gspDialect.getViewDefinition(metaData.getConnection(), tableMeta.getName(), tableMeta);
            viewAnalyzer = new ViewAnalyzer();
            viewAnalyzer.parse(sql);
            if (viewAnalyzer.isSimple()) {
                tableName = viewAnalyzer.getTableName();
            } else {
                return Collections.emptyList();
            }
        }
        ResultSet rs = metaData.getImportedKeys(tableMeta.getCatalogName(), tableMeta.getSchemaName(),
                tableName);
        try {
            while (rs.next()) {
                String name = rs.getString("FK_NAME");
                if (!map.containsKey(name)) {
                    DbForeignKeyMeta fkMeta = new DbForeignKeyMeta();
                    fkMeta.setName(name);
                    fkMeta.setPrimaryKeyCatalogName(rs.getString("PKTABLE_CAT"));
                    fkMeta.setPrimaryKeySchemaName(rs.getString("PKTABLE_SCHEM"));
                    fkMeta.setPrimaryKeyTableName(rs.getString("PKTABLE_NAME"));
                    map.put(name, fkMeta);
                }
                DbForeignKeyMeta fkMeta = map.get(name);
                fkMeta.addPrimaryKeyColumnName(rs.getString("PKCOLUMN_NAME"));
                fkMeta.addForeignKeyColumnName(rs.getString("FKCOLUMN_NAME"));
            }
        } finally {
            ResultSetUtil.close(rs);
        }
        if (viewAnalyzer != null && !map.isEmpty()) {

            Map<String, DbForeignKeyMeta> tmpMap = new ArrayMap(map);

            for (DbForeignKeyMeta fkMeta : tmpMap.values()) {
                boolean fkContains = true;
                for (String fkColumn : fkMeta.getForeignKeyColumnNameList()) {
                    fkContains &= viewAnalyzer.getColumnNames().contains(fkColumn.toUpperCase());
                }
                if (!fkContains)
                    map.remove(fkMeta.getName());
            }
        }

        DbForeignKeyMeta[] array = map.values().toArray(new DbForeignKeyMeta[map.size()]);
        return Arrays.asList(array);
    } catch (SQLException ex) {
        throw new SQLRuntimeException(ex);
    }
}

From source file:org.acmsl.queryj.metadata.engines.MetadataManagerTableDAO.java

/**
 * Queries the contents of given table.//from   w ww. j a  va2  s  . co  m
 * @param tableName the table name.
 * @param staticAttributeName the name of the static attribute.
 * @param attributes the attributes.
 * @param metaData the metadata.
 * @return the retrieved rows.
 * @throws SQLException if the contents cannot be retrieved.
 */
@NotNull
protected List<Row<String>> queryContents(@NotNull final String tableName,
        @Nullable final String staticAttributeName, @NotNull final List<Attribute<String>> attributes,
        @NotNull final DatabaseMetaData metaData) throws SQLException {
    return queryContents(tableName, staticAttributeName, attributes, metaData.getConnection());
}

From source file:org.acmsl.queryj.metadata.engines.oracle.OracleMetadataManager.java

/**
 * {@inheritDoc}/* w w w  .jav  a  2 s  . c o  m*/
 */
@NotNull
@Override
@SuppressWarnings("unused")
protected List<Table<String, Attribute<String>, List<Attribute<String>>>> extractTableMetadata(
        @Nullable final List<String> tableNames, @NotNull final DatabaseMetaData metaData,
        @Nullable final String catalog, @Nullable final String schema, final boolean caseSensitiveness,
        @NotNull final MetadataExtractionListener metadataExtractionListener,
        @NotNull final MetaLanguageUtils metaLanguageUtils) throws SQLException, QueryJException {
    return extractTableMetadata(tableNames, metaData.getConnection(), caseSensitiveness,
            metadataExtractionListener, metaLanguageUtils, getMetadataTypeManager());
}

From source file:org.apache.bigtop.itest.hive.TestJdbc.java

/**
 * Test simple DatabaseMetaData calls.  getColumns is tested elsewhere, as we need to call
 * that on a valid table.  Same with getFunctions.
 *
 * @throws SQLException//w  w w.  j  ava 2 s .c  om
 */
@Test
public void databaseMetaDataCalls() throws SQLException {
    DatabaseMetaData md = conn.getMetaData();

    boolean boolrc = md.allTablesAreSelectable();
    LOG.debug("All tables are selectable? " + boolrc);

    String strrc = md.getCatalogSeparator();
    LOG.debug("Catalog separator " + strrc);

    strrc = md.getCatalogTerm();
    LOG.debug("Catalog term " + strrc);

    ResultSet rs = md.getCatalogs();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found catalog " + strrc);
    }

    Connection c = md.getConnection();

    int intrc = md.getDatabaseMajorVersion();
    LOG.debug("DB major version is " + intrc);

    intrc = md.getDatabaseMinorVersion();
    LOG.debug("DB minor version is " + intrc);

    strrc = md.getDatabaseProductName();
    LOG.debug("DB product name is " + strrc);

    strrc = md.getDatabaseProductVersion();
    LOG.debug("DB product version is " + strrc);

    intrc = md.getDefaultTransactionIsolation();
    LOG.debug("Default transaction isolation is " + intrc);

    intrc = md.getDriverMajorVersion();
    LOG.debug("Driver major version is " + intrc);

    intrc = md.getDriverMinorVersion();
    LOG.debug("Driver minor version is " + intrc);

    strrc = md.getDriverName();
    LOG.debug("Driver name is " + strrc);

    strrc = md.getDriverVersion();
    LOG.debug("Driver version is " + strrc);

    strrc = md.getExtraNameCharacters();
    LOG.debug("Extra name characters is " + strrc);

    strrc = md.getIdentifierQuoteString();
    LOG.debug("Identifier quote string is " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getImportedKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getIndexInfo("a", "b", "d", true, true);

    intrc = md.getJDBCMajorVersion();
    LOG.debug("JDBC major version is " + intrc);

    intrc = md.getJDBCMinorVersion();
    LOG.debug("JDBC minor version is " + intrc);

    intrc = md.getMaxColumnNameLength();
    LOG.debug("Maximum column name length is " + intrc);

    strrc = md.getNumericFunctions();
    LOG.debug("Numeric functions are " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getPrimaryKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedureColumns("a", "b", "d", "e");

    strrc = md.getProcedureTerm();
    LOG.debug("Procedures are called " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedures("a", "b", "d");

    strrc = md.getSchemaTerm();
    LOG.debug("Schemas are called " + strrc);

    rs = md.getSchemas();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found schema " + strrc);
    }

    strrc = md.getSearchStringEscape();
    LOG.debug("Search string escape is " + strrc);

    strrc = md.getStringFunctions();
    LOG.debug("String functions are " + strrc);

    strrc = md.getSystemFunctions();
    LOG.debug("System functions are " + strrc);

    rs = md.getTableTypes();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found table type " + strrc);
    }

    strrc = md.getTimeDateFunctions();
    LOG.debug("Time/date functions are " + strrc);

    rs = md.getTypeInfo();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found type " + strrc);
    }

    // In Hive 1.2 this always returns an empty RS
    rs = md.getUDTs("a", "b", "d", null);

    boolrc = md.supportsAlterTableWithAddColumn();
    LOG.debug("Supports alter table with add column? " + boolrc);

    boolrc = md.supportsAlterTableWithDropColumn();
    LOG.debug("Supports alter table with drop column? " + boolrc);

    boolrc = md.supportsBatchUpdates();
    LOG.debug("Supports batch updates? " + boolrc);

    boolrc = md.supportsCatalogsInDataManipulation();
    LOG.debug("Supports catalogs in data manipulation? " + boolrc);

    boolrc = md.supportsCatalogsInIndexDefinitions();
    LOG.debug("Supports catalogs in index definition? " + boolrc);

    boolrc = md.supportsCatalogsInPrivilegeDefinitions();
    LOG.debug("Supports catalogs in privilege definition? " + boolrc);

    boolrc = md.supportsCatalogsInProcedureCalls();
    LOG.debug("Supports catalogs in procedure calls? " + boolrc);

    boolrc = md.supportsCatalogsInTableDefinitions();
    LOG.debug("Supports catalogs in table definition? " + boolrc);

    boolrc = md.supportsColumnAliasing();
    LOG.debug("Supports column aliasing? " + boolrc);

    boolrc = md.supportsFullOuterJoins();
    LOG.debug("Supports full outer joins? " + boolrc);

    boolrc = md.supportsGroupBy();
    LOG.debug("Supports group by? " + boolrc);

    boolrc = md.supportsLimitedOuterJoins();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsMultipleResultSets();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsNonNullableColumns();
    LOG.debug("Supports non-nullable columns? " + boolrc);

    boolrc = md.supportsOuterJoins();
    LOG.debug("Supports outer joins? " + boolrc);

    boolrc = md.supportsPositionedDelete();
    LOG.debug("Supports positioned delete? " + boolrc);

    boolrc = md.supportsPositionedUpdate();
    LOG.debug("Supports positioned update? " + boolrc);

    boolrc = md.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set holdability? " + boolrc);

    boolrc = md.supportsResultSetType(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set type? " + boolrc);

    boolrc = md.supportsSavepoints();
    LOG.debug("Supports savepoints? " + boolrc);

    boolrc = md.supportsSchemasInDataManipulation();
    LOG.debug("Supports schemas in data manipulation? " + boolrc);

    boolrc = md.supportsSchemasInIndexDefinitions();
    LOG.debug("Supports schemas in index definitions? " + boolrc);

    boolrc = md.supportsSchemasInPrivilegeDefinitions();
    LOG.debug("Supports schemas in privilege definitions? " + boolrc);

    boolrc = md.supportsSchemasInProcedureCalls();
    LOG.debug("Supports schemas in procedure calls? " + boolrc);

    boolrc = md.supportsSchemasInTableDefinitions();
    LOG.debug("Supports schemas in table definitions? " + boolrc);

    boolrc = md.supportsSelectForUpdate();
    LOG.debug("Supports select for update? " + boolrc);

    boolrc = md.supportsStoredProcedures();
    LOG.debug("Supports stored procedures? " + boolrc);

    boolrc = md.supportsTransactions();
    LOG.debug("Supports transactions? " + boolrc);

    boolrc = md.supportsUnion();
    LOG.debug("Supports union? " + boolrc);

    boolrc = md.supportsUnionAll();
    LOG.debug("Supports union all? " + boolrc);

}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

@Test
public void testParentReferences() throws Exception {
    /* Test parent references from Statement */
    Statement s = this.con.createStatement();
    ResultSet rs = s.executeQuery("SELECT * FROM " + dataTypeTableName);

    assertTrue(s.getConnection() == this.con);
    assertTrue(rs.getStatement() == s);// ww w .  j av a  2s .  c om

    rs.close();
    s.close();

    /* Test parent references from PreparedStatement */
    PreparedStatement ps = this.con.prepareStatement("SELECT * FROM " + dataTypeTableName);
    rs = ps.executeQuery();

    assertTrue(ps.getConnection() == this.con);
    assertTrue(rs.getStatement() == ps);

    rs.close();
    ps.close();

    /* Test DatabaseMetaData queries which do not have a parent Statement */
    DatabaseMetaData md = this.con.getMetaData();

    assertTrue(md.getConnection() == this.con);

    rs = md.getCatalogs();
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getColumns(null, null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getFunctions(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getImportedKeys(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getPrimaryKeys(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getProcedureColumns(null, null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getProcedures(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getSchemas();
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getTableTypes();
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getTables(null, null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getTypeInfo();
    assertNull(rs.getStatement());
    rs.close();
}

From source file:org.apache.hive.jdbc.TestJdbcWithMiniHS2.java

@Test
public void testTempTable() throws Exception {
    // Create temp table with current connection
    String tempTableName = "tmp1";
    Statement stmt = conTestDb.createStatement();
    stmt.execute("CREATE TEMPORARY TABLE " + tempTableName + " (key string, value string)");
    stmt.execute("load data local inpath '" + kvDataFilePath.toString() + "' into table " + tempTableName);

    String resultVal = "val_238";
    String queryStr = "SELECT * FROM " + tempTableName + " where value = '" + resultVal + "'";

    ResultSet res = stmt.executeQuery(queryStr);
    assertTrue(res.next());//from   w  w w. j  a  v a  2s.c o  m
    assertEquals(resultVal, res.getString(2));
    res.close();
    stmt.close();

    // Test getTables()
    DatabaseMetaData md = conTestDb.getMetaData();
    assertTrue(md.getConnection() == conTestDb);

    ResultSet rs = md.getTables(null, null, tempTableName, null);
    boolean foundTable = false;
    while (rs.next()) {
        String tableName = rs.getString(3);
        if (tableName.equalsIgnoreCase(tempTableName)) {
            assertFalse("Table not found yet", foundTable);
            foundTable = true;
        }
    }
    assertTrue("Found temp table", foundTable);

    // Test getTables() with no table name pattern
    rs = md.getTables(null, null, null, null);
    foundTable = false;
    while (rs.next()) {
        String tableName = rs.getString(3);
        if (tableName.equalsIgnoreCase(tempTableName)) {
            assertFalse("Table not found yet", foundTable);
            foundTable = true;
        }
    }
    assertTrue("Found temp table", foundTable);

    // Test getColumns()
    rs = md.getColumns(null, null, tempTableName, null);
    assertTrue("First row", rs.next());
    assertTrue(rs.getString(3).equalsIgnoreCase(tempTableName));
    assertTrue(rs.getString(4).equalsIgnoreCase("key"));
    assertEquals(Types.VARCHAR, rs.getInt(5));

    assertTrue("Second row", rs.next());
    assertTrue(rs.getString(3).equalsIgnoreCase(tempTableName));
    assertTrue(rs.getString(4).equalsIgnoreCase("value"));
    assertEquals(Types.VARCHAR, rs.getInt(5));

    // A second connection should not be able to see the table
    Connection conn2 = DriverManager.getConnection(miniHS2.getJdbcURL(testDbName),
            System.getProperty("user.name"), "bar");
    Statement stmt2 = conn2.createStatement();
    stmt2.execute("USE " + testDbName);
    boolean gotException = false;
    try {
        res = stmt2.executeQuery(queryStr);
    } catch (SQLException err) {
        // This is expected to fail.
        assertTrue("Expecting table not found error, instead got: " + err,
                err.getMessage().contains("Table not found"));
        gotException = true;
    }
    assertTrue("Exception while querying non-existing temp table", gotException);
    conn2.close();
}