Example usage for java.sql DatabaseMetaData getDatabaseProductName

List of usage examples for java.sql DatabaseMetaData getDatabaseProductName

Introduction

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

Prototype

String getDatabaseProductName() throws SQLException;

Source Link

Document

Retrieves the name of this database product.

Usage

From source file:jef.database.DbMetaData.java

/**
 * ??/*from   www  .  ja v a  2 s.  c  om*/
 * 
 * @return Map<String,String> [key] is
 *         <ul>
 *         <li>DatabaseProductName</li>
 *         <li>DatabaseProductVersion</li>
 *         <li>DriverName</li>
 *         <li>DriverVersion</li>
 *         </ul>
 */
public Map<String, String> getDbVersion() throws SQLException {
    Connection conn = getConnection(false);
    DatabaseMetaData databaseMetaData = conn.getMetaData();
    Map<String, String> map = new SimpleMap<String, String>();
    map.put("DriverName", databaseMetaData.getDriverName());
    map.put("DriverVersion",
            databaseMetaData.getDriverVersion() + " " + databaseMetaData.getDatabaseMinorVersion());
    map.put("DatabaseProductName", databaseMetaData.getDatabaseProductName());
    map.put("DatabaseProductVersion",
            databaseMetaData.getDatabaseProductVersion() + " " + databaseMetaData.getDatabaseMinorVersion());

    String otherVersionSQL = info.profile.getProperty(DbProperty.OTHER_VERSION_SQL);
    if (otherVersionSQL != null) {
        for (String sql : StringUtils.split(otherVersionSQL, ";")) {
            if (StringUtils.isBlank(sql))
                continue;
            Statement st = conn.createStatement();
            ResultSet rs = null;
            try {
                rs = st.executeQuery(sql);
                while (rs.next()) {
                    map.put(rs.getString(1), rs.getString(2));
                }
            } finally {
                DbUtils.close(rs);
                DbUtils.close(st);
            }
        }
    }
    releaseConnection(conn);
    return map;
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

public String getServerName() throws WGAPIException {

    try {//from www . j a  v  a2s .  co m
        DatabaseMetaData metaData = getSession().doReturningWork(new ReturningWork<DatabaseMetaData>() {
            public DatabaseMetaData execute(Connection connection) throws SQLException {
                return connection.getMetaData();
            }
        });
        return metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion();
    } catch (HibernateException e) {
        throw new WGBackendException("Error retrieving server name", e);
    } catch (SQLException e) {
        throw new WGBackendException("Error retrieving server name", e);
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

/**
 * This method is called when the dictionary first sees any connection.
 * It is used to initialize dictionary metadata if needed. If you
 * override this method, be sure to call
 * <code>super.connectedConfiguration</code>.
 *//*www .jav a  2s  .  c  o  m*/
public void connectedConfiguration(Connection conn) throws SQLException {
    if (!connected) {
        DatabaseMetaData metaData = null;
        try {
            metaData = conn.getMetaData();

            databaseProductName = nullSafe(metaData.getDatabaseProductName());
            databaseProductVersion = nullSafe(metaData.getDatabaseProductVersion());
            setMajorVersion(metaData.getDatabaseMajorVersion());
            setMinorVersion(metaData.getDatabaseMinorVersion());
            try {
                // JDBC3-only method, so it might throw an
                // AbstractMethodError
                int JDBCMajorVersion = metaData.getJDBCMajorVersion();
                isJDBC3 = JDBCMajorVersion >= 3;
                isJDBC4 = JDBCMajorVersion >= 4;
            } catch (Throwable t) {
                // ignore if not JDBC3
            }
        } catch (Exception e) {
            if (log.isTraceEnabled())
                log.trace(e.toString(), e);
        }

        if (log.isTraceEnabled()) {
            log.trace(DBDictionaryFactory.toString(metaData));

            if (isJDBC3) {
                try {
                    log.trace(_loc.get("connection-defaults", new Object[] { conn.getAutoCommit(),
                            conn.getHoldability(), conn.getTransactionIsolation() }));
                } catch (Throwable t) {
                    log.trace("Unable to trace connection settings", t);
                }
            }
        }

        // Configure the naming utility
        if (supportsDelimitedIdentifiers == null) // not explicitly set
            configureNamingUtil(metaData);

        // Auto-detect generated keys retrieval support unless user specified it.
        if (supportsGetGeneratedKeys == null) {
            supportsGetGeneratedKeys = (isJDBC3) ? metaData.supportsGetGeneratedKeys() : false;
        }
        if (log.isInfoEnabled()) {
            log.info(_loc.get("dict-info", new Object[] { metaData.getDatabaseProductName(), getMajorVersion(),
                    getMinorVersion(), metaData.getDriverName(), metaData.getDriverVersion() }));
        }
    }
    connected = true;
}

From source file:org.talend.metadata.managment.model.DBConnectionFillerImpl.java

@Override
public List<Catalog> fillCatalogs(DatabaseConnection dbConn, DatabaseMetaData dbJDBCMetadata,
        IMetadataConnection metaConnection, List<String> catalogFilter) {
    List<Catalog> catalogList = new ArrayList<Catalog>();
    if (dbJDBCMetadata == null) {
        return null;
    }/* w  ww  .  j  a va2  s.co m*/

    if (ConnectionUtils.isPostgresql(dbJDBCMetadata)) {
        return fillPostgresqlCatalogs(metaConnection, dbConn, dbJDBCMetadata, catalogList);
    }

    // TDI-17172 : if the catalog is not fill, as the db context model, should clear "catalogFilter" .
    if (dbConn != null && dbConn.isContextMode()) {
        if (EDatabaseTypeName.MYSQL.getProduct().equals(dbConn.getProductId())
                || EDatabaseTypeName.MSSQL.getProduct().equals(dbConn.getProductId())
                || EDatabaseTypeName.MSSQL05_08.getProduct().equals(dbConn.getProductId())) {
            IMetadataConnection iMetadataCon = metaConnection;
            if (iMetadataCon == null) {
                iMetadataCon = ConvertionHelper.convert(dbConn);
            }
            if (iMetadataCon != null) {
                String catalogTemp = iMetadataCon.getDatabase();
                if ("".equals(catalogTemp)) { //$NON-NLS-1$
                    catalogFilter.clear();
                }
            }
        }
    }

    try {
        if (!isDbSupportCatalogNames(dbJDBCMetadata)) {
            return catalogList;
        }
        if (!isDbHasCatalogs(dbJDBCMetadata)) {
            ConnectionHelper.removeAllPackages(dbConn);
            return catalogList;
        }
        ResultSet catalogNames = null;
        if (dbJDBCMetadata instanceof SybaseDatabaseMetaData) {
            catalogNames = ((SybaseDatabaseMetaData) dbJDBCMetadata).getCatalogs(dbConn.getUsername());
        } else {
            catalogNames = dbJDBCMetadata.getCatalogs();
        }
        // this filter is for filter schema later
        List<String> schemaFilterList = new ArrayList<String>();
        if (catalogNames != null) {
            boolean isHive = MetadataConnectionUtils.isHive(dbJDBCMetadata);
            boolean isSybase = MetadataConnectionUtils.isSybase(dbJDBCMetadata);
            // else DB support getCatalogs() method
            while (catalogNames.next()) {
                // MOD xqliu 2009-11-03 bug 9841
                String catalogName = null;
                try {
                    String temp = null;
                    // since hive don't support some methods
                    if (isHive) {
                        temp = MetaDataConstants.TABLE_CAT.name();
                    } else {
                        temp = MetadataConnectionUtils.isOdbcPostgresql(dbJDBCMetadata)
                                ? DatabaseConstant.ODBC_POSTGRESQL_CATALOG_NAME
                                : MetaDataConstants.TABLE_CAT.name();
                    }
                    catalogName = catalogNames.getString(temp);
                    // MOD zshen filter ODBC catalog
                    // FIXME isODBCCatalog is not a good name
                    if (!isHive && !MetadataConnectionUtils.isODBCCatalog(catalogName, dbJDBCMetadata)) {
                        continue;
                    }
                } catch (Exception e) {
                    log.warn(e, e);
                    if (dbJDBCMetadata.getDatabaseProductName() != null
                            && dbJDBCMetadata.getDatabaseProductName().toLowerCase()
                                    .indexOf(DatabaseConstant.POSTGRESQL_PRODUCT_NAME) > -1) {
                        catalogName = ""; //$NON-NLS-1$
                    }
                }
                // Changed by Marvin Wang on Jan. 6, 2012 for bug TDI-24222. I haved discussed with Shen Ze about
                // the fix,it is okay for them. What we did is to avoid creating a new catalog when catalogName is
                // "null" for DB2.
                if (catalogName != null) {
                    // MOD xqliu 2010-03-03 feature 11412

                    if (!isNullSID(dbConn) && dbConn != null
                            && !dbConn.getDatabaseType().equals(EDatabaseTypeName.AS400.getDisplayName())
                            && !dbConn.getDatabaseType()
                                    .equals(EDatabaseTypeName.HSQLDB_IN_PROGRESS.getDisplayName())
                            && !dbConn.getDatabaseType()
                                    .equals(EDatabaseTypeName.HSQLDB_SERVER.getDisplayName())
                            && !dbConn.getDatabaseType()
                                    .equals(EDatabaseTypeName.HSQLDB_WEBSERVER.getDisplayName())) {
                        String databaseOnConnWizard = getDatabaseName(dbConn);

                        // If the SID on ui is not empty, the catalog name should be same to this SID name.
                        postFillCatalog(catalogList, catalogFilter, schemaFilterList,
                                TalendCWMService.getReadableName(dbConn, databaseOnConnWizard), dbConn);
                        break;
                    } else if (isCreateElement(catalogFilter, catalogName)) {
                        postFillCatalog(catalogList, catalogFilter, schemaFilterList, catalogName, dbConn);
                    }
                }
                // ~11412
            }
            // --- release the result set.
            catalogNames.close();
            if (!isHive) {
                List<Catalog> removeCatalogList = new ArrayList<Catalog>();
                for (Catalog catalog : catalogList) {
                    List<Schema> schemaList = new ArrayList<Schema>();
                    try {
                        schemaList = fillSchemaToCatalog(dbConn, dbJDBCMetadata, catalog, schemaFilterList);
                        if (!schemaList.isEmpty() && schemaList.size() > 0) {
                            CatalogHelper.addSchemas(schemaList, catalog);
                        }
                    } catch (Throwable e) {
                        removeCatalogList.add(catalog);
                    }
                }
                // TDQ-1625
                if (isSybase && catalogFilter != null && !catalogFilter.isEmpty() && catalogFilter.size() > 0
                        && catalogList.isEmpty() && catalogList.size() == 0) {
                    catalogFilter.clear();
                    return fillCatalogs(dbConn, dbJDBCMetadata, catalogFilter);
                }
                catalogList.removeAll(removeCatalogList);
            }

            Set<MetadataTable> tableSet = ConnectionHelper.getTables(dbConn);
            // replaceCatalogs is use for record tables when click finish, then set to current connection.
            List<Catalog> replaceCatalogs = new ArrayList<Catalog>();
            List<String> catalogName = new ArrayList<String>();
            for (MetadataTable table : tableSet) {
                EObject eContainer = table.eContainer();
                if (eContainer != null) {
                    if (eContainer instanceof Catalog) {
                        Catalog c = (Catalog) eContainer;
                        String name = c.getName();
                        if (!catalogName.contains(name)) {
                            replaceCatalogs.add(c);
                            catalogName.add(name);
                        }
                    } else if (eContainer instanceof Schema) {
                        EObject parent = eContainer.eContainer();
                        if (parent != null && parent instanceof Catalog) {
                            Catalog c = (Catalog) parent;
                            String name = c.getName();
                            if (!catalogName.contains(name)) {
                                List<Schema> filterSchemas = new ArrayList<Schema>();
                                List<String> schemaName = new ArrayList<String>();
                                List<Schema> schemas = CatalogHelper.getSchemas(c);
                                for (Schema schema : schemas) {
                                    if (schemaFilterList != null) {
                                        if (schemaFilterList.contains(schema.getName())) {
                                            filterSchemas.add(schema);
                                            schemaName.add(schema.getName());
                                        } else if (schema.getOwnedElement() != null
                                                && !schema.getOwnedElement().isEmpty()) {
                                            filterSchemas.add(schema);
                                            schemaName.add(schema.getName());
                                        }
                                    }
                                }
                                // get schema in current connection
                                for (Catalog catalog : catalogList) {
                                    if (catalog.getName().equals(name)) {
                                        boolean added = false;
                                        for (Schema schema : CatalogHelper.getSchemas(catalog)) {
                                            if (!schemaName.contains(schema.getName())) {
                                                filterSchemas.add(schema);
                                                added = true;
                                            }
                                        }
                                        if (added) {
                                            break;
                                        }
                                    }
                                }

                                c.getOwnedElement().clear();
                                CatalogHelper.addSchemas(filterSchemas, c);
                                replaceCatalogs.add(c);
                                catalogName.add(name);
                            }
                        }
                    }
                }
            }
            if (this.isLinked() && !catalogList.isEmpty()) {
                ConnectionHelper.addCatalogs(catalogList, dbConn);
            }
            // if have same schema in current connection,need to fill tables.
            for (Catalog catalog : replaceCatalogs) {
                List<Catalog> list = new ArrayList<Catalog>();
                String name = catalog.getName();
                Catalog c = (Catalog) ConnectionHelper.getPackage(name, dbConn, Catalog.class);
                if (c != null) {
                    list.add(c);
                    ConnectionHelper.removeCatalogs(list, dbConn);
                    ConnectionHelper.addCatalog(catalog, dbConn);
                } else {
                    ConnectionHelper.addCatalog(catalog, dbConn);
                }
            }
        }
    } catch (SQLException e) {
        log.warn("JDBC getCatalogs() method is not available with this driver.", e); //$NON-NLS-1$
    }

    return catalogList;
}

From source file:org.talend.metadata.managment.model.DBConnectionFillerImpl.java

@Override
public List<MetadataTable> fillAll(Package pack, DatabaseMetaData dbJDBCMetadata,
        IMetadataConnection metaConnection, List<String> tableFilter, String tablePattern, String[] tableType) {

    List<MetadataTable> list = new ArrayList<MetadataTable>();
    if (dbJDBCMetadata == null) {
        return null;
    }/*from  www. j a  v  a2 s .  c  om*/
    ExtractMetaDataUtils extractMeta = ExtractMetaDataUtils.getInstance();
    Package catalogOrSchema = PackageHelper.getCatalogOrSchema(pack);
    String catalogName = null;
    String schemaPattern = null;

    if (catalogOrSchema != null) {
        // catalog
        if (catalogOrSchema instanceof Catalog) {
            catalogName = catalogOrSchema.getName();
        } else {// schema
            Package parentCatalog = PackageHelper.getParentPackage(catalogOrSchema);
            // in the fillSchema, we set one default schema with " ", but this one doesn't exist, so we should
            // replace to get the tables from all schemas instead
            schemaPattern = " ".equals(catalogOrSchema.getName()) ? null : catalogOrSchema.getName(); //$NON-NLS-1$
            catalogName = parentCatalog == null ? null : parentCatalog.getName();
        }
    }
    try {
        // common
        boolean isOracle8i = true;
        boolean isOracle = false;
        boolean isOracleJdbc = false;
        String tableComment = null;
        List<String> tablesToFilter = new ArrayList<String>();
        if (pack != null) {
            Connection c = ConnectionHelper.getConnection(pack);
            isOracle8i = MetadataConnectionUtils.isOracle8i(c);
            isOracle = MetadataConnectionUtils.isOracle(c);
            isOracleJdbc = MetadataConnectionUtils.isOracleJDBC(c);
            if ((isOracleJdbc || isOracle) && !isOracle8i) {// oracle and not oracle8
                Statement stmt;
                try {
                    // MOD qiongli TDQ-4732 use the common method to create statement both DI and DQ,avoid Exception
                    // for top.
                    stmt = dbJDBCMetadata.getConnection().createStatement();
                    ResultSet rsTables = stmt.executeQuery(TableInfoParameters.ORACLE_10G_RECBIN_SQL);
                    tablesToFilter = ExtractMetaDataFromDataBase.getTableNamesFromQuery(rsTables,
                            dbJDBCMetadata.getConnection());
                    rsTables.close();
                    stmt.close();
                } catch (SQLException e) {
                    ExceptionHandler.process(e);
                }
            }
        }

        boolean isHive2 = HiveConnectionManager.getInstance().isHive2(metaConnection);
        if (isHive2) {
            // for CDH4 HIVE2 , the table type are MANAGED_TABLE and EXTERNAL_TABLE ......
            // tableType = null;
        }
        ResultSet tables = dbJDBCMetadata.getTables(catalogName, schemaPattern, tablePattern, tableType);

        while (tables.next()) {
            String coloumnName = GetTable.TABLE_SCHEM.name();
            if (schemaPattern != null) {
                try {
                    tables.getString(coloumnName);
                } catch (Exception e) {
                    coloumnName = GetTable.TABLE_SCHEMA.name();
                }
            }
            String tableName = getStringFromResultSet(tables, GetTable.TABLE_NAME.name());
            String temptableType = getStringFromResultSet(tables, GetTable.TABLE_TYPE.name());

            // for special db. teradata_sql_model/db2_zos/as400
            temptableType = convertSpecialTableType(temptableType);
            // for
            if (!isCreateElement(tableFilter, tableName)) {
                continue;
            }
            if (tableName == null || tablesToFilter.contains(tableName)) {
                continue;
            }
            //                if (!isOracle && !isOracle8i && !isOracleJdbc && tableName.startsWith("/")) { //$NON-NLS-1$
            // continue;
            // }
            if (!isOracle8i) {
                tableComment = getTableComment(dbJDBCMetadata, tables, tableName, catalogName, schemaPattern);
            }
            MetadataTable metadatatable = null;
            if (TableType.VIEW.toString().equals(temptableType)
                    || ETableTypes.VIRTUAL_VIEW.getName().equals(temptableType)) {
                metadatatable = RelationalFactory.eINSTANCE.createTdView();
            } else {
                metadatatable = RelationalFactory.eINSTANCE.createTdTable();
            }

            metadatatable.setName(tableName);
            // Added by Marvin Wang on Feb. 6, 2012 for bug TDI-24413, it is just for hive external table.
            if (ETableTypes.TABLETYPE_EXTERNAL_TABLE.getName().equals(temptableType)
                    || ETableTypes.EXTERNAL_TABLE.getName().equals(temptableType)
                    || ETableTypes.MANAGED_TABLE.getName().equals(temptableType)
                    || ETableTypes.INDEX_TABLE.getName().equals(temptableType)) {
                metadatatable.setTableType(ETableTypes.TABLETYPE_TABLE.getName());
            } else if (ETableTypes.VIRTUAL_VIEW.getName().equals(temptableType)) {
                metadatatable.setTableType(ETableTypes.TABLETYPE_VIEW.getName());
            } else {
                metadatatable.setTableType(temptableType);
            }
            metadatatable.setLabel(metadatatable.getName());
            if (tableComment != null) {
                metadatatable.setComment(tableComment);
                ColumnSetHelper.setComment(tableComment, metadatatable);
            }
            try {
                if (tables.getString("SYSTEM_TABLE_NAME") != null //$NON-NLS-1$
                        && tables.getString("SYSTEM_TABLE_SCHEMA") != null //$NON-NLS-1$
                        && tables.getString("TABLE_SCHEMA") != null) { //$NON-NLS-1$
                    TaggedValueHelper.setTaggedValue(metadatatable, TaggedValueHelper.SYSTEMTABLENAME,
                            tables.getString("SYSTEM_TABLE_NAME").trim()); //$NON-NLS-1$
                    TaggedValueHelper.setTaggedValue(metadatatable, TaggedValueHelper.SYSTEMTABLESCHEMA,
                            tables.getString("SYSTEM_TABLE_SCHEMA").trim()); //$NON-NLS-1$
                    TaggedValueHelper.setTaggedValue(metadatatable, TaggedValueHelper.TABLESCHEMA,
                            tables.getString("TABLE_SCHEMA").trim()); //$NON-NLS-1$
                }
            } catch (SQLException e) {
                // don't catch anything if the system table name or schema doesn't exist
                // this part is needed only for as400
            }
            list.add(metadatatable);
        }
        if (dbJDBCMetadata.getDatabaseProductName() != null
                && dbJDBCMetadata.getDatabaseProductName().equals("Microsoft SQL Server")) { //$NON-NLS-1$
            for (String element : tableType) {
                if (element.equals("SYNONYM")) { //$NON-NLS-1$
                    Statement stmt = extractMeta.getConn().createStatement();
                    extractMeta.setQueryStatementTimeout(stmt);
                    String schemaname = schemaPattern + ".sysobjects"; //$NON-NLS-1$
                    String sql = "select name from " + schemaname + " where xtype='SN'"; //$NON-NLS-1$//$NON-NLS-2$
                    if ("dbo".equalsIgnoreCase(schemaPattern)) { //$NON-NLS-1$
                        // SELECT name AS object_name ,SCHEMA_NAME(schema_id) AS schema_name FROM sys.objects where
                        // type='SN'
                        ResultSet rsTables = stmt.executeQuery(sql);
                        while (rsTables.next()) {
                            String nameKey = rsTables.getString("name").trim(); //$NON-NLS-1$

                            MetadataTable metadatatable = null;
                            metadatatable = RelationalFactory.eINSTANCE.createTdTable();

                            metadatatable.setName(nameKey);
                            metadatatable.setTableType(ETableTypes.TABLETYPE_SYNONYM.getName());
                            metadatatable.setLabel(metadatatable.getName());
                            list.add(metadatatable);
                        }
                    }
                }
            }
        } else if (dbJDBCMetadata.getDatabaseProductName() != null
                && dbJDBCMetadata.getDatabaseProductName().startsWith("DB2/")) { //$NON-NLS-1$
            for (String element : tableType) {
                if (element.equals("SYNONYM")) { //$NON-NLS-1$
                    Statement stmt = extractMeta.getConn().createStatement();
                    extractMeta.setQueryStatementTimeout(stmt);
                    String sql = "SELECT NAME FROM SYSIBM.SYSTABLES where TYPE='A' and BASE_SCHEMA = '" //$NON-NLS-1$
                            + schemaPattern + "'"; //$NON-NLS-1$
                    ResultSet rsTables = stmt.executeQuery(sql);
                    while (rsTables.next()) {
                        String nameKey = rsTables.getString("NAME").trim(); //$NON-NLS-1$

                        MetadataTable metadatatable = null;
                        metadatatable = RelationalFactory.eINSTANCE.createTdTable();

                        metadatatable.setName(nameKey);
                        metadatatable.setTableType(ETableTypes.TABLETYPE_SYNONYM.getName());
                        metadatatable.setLabel(metadatatable.getName());
                        list.add(metadatatable);
                    }
                }
            }
        }
        if (isLinked()) {
            PackageHelper.addMetadataTable(ListUtils.castList(MetadataTable.class, list), pack);
        }
    } catch (SQLException e) {
        log.error(e, e);
    }

    return list;

}