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:org.phenotips.pingback.internal.client.data.DatabasePingDataProvider.java

@Override
public Map<String, Object> provideData() {
    Map<String, Object> jsonMap = new HashMap<>();
    DatabaseMetaData metaData;
    try {/*www  . j  a  va 2s.  c  om*/
        metaData = getDatabaseMetaData();
    } catch (Exception e) {
        // Ignore, we just don't save DB information...
        // However we log a warning since it's a problem that needs to be seen and looked at.
        logWarning("Failed to retrieve database metadata", e);
        metaData = null;
    }

    if (metaData != null) {
        try {
            jsonMap.put(PROPERTY_DB_NAME, metaData.getDatabaseProductName());
        } catch (SQLException e) {
            // Ignore, we just don't save that information...
            // However we log a warning since it's a problem that needs to be seen and looked at.
            logWarning("Failed to compute the database product name", e);
        }
        try {
            jsonMap.put(PROPERTY_DB_VERSION, metaData.getDatabaseProductVersion());
        } catch (SQLException e) {
            // Ignore, we just don't save that information...
            // However we log a warning since it's a problem that needs to be seen and looked at.
            logWarning("Failed to compute the database product version", e);
        }
    }
    return jsonMap;
}

From source file:org.talend.core.model.metadata.builder.database.manager.dbs.OracleExtractManager.java

@Override
protected void fillSynonyms(IMetadataConnection metadataConnection, List<TdColumn> metadataColumns,
        NamedColumnSet table, String tableName, DatabaseMetaData dbMetaData) throws SQLException {
    if (metadataConnection == null || dbMetaData == null) {
        return;/*w  w  w.  ja  v a  2  s . c om*/
    }
    if (dbMetaData.getDatabaseProductName().equals(OracleExtractManager.DATABASE_PRODUCT_NAME)) {
        ExtractMetaDataUtils extractMeta = ExtractMetaDataUtils.getInstance();
        // need to retrieve columns of synonym by useing sql rather than get them from jdbc metadata
        String synSQL = "SELECT all_tab_columns.*\n" + "FROM all_tab_columns\n"
                + "LEFT OUTER JOIN all_synonyms\n" + "ON all_tab_columns.TABLE_NAME = all_synonyms.TABLE_NAME\n"
                + "AND ALL_SYNONYMS.TABLE_OWNER = all_tab_columns.OWNER\n" + "WHERE all_synonyms.SYNONYM_NAME ="
                + "\'" + tableName + "\'\n";
        // bug TDI-19382
        if (!("").equals(metadataConnection.getSchema())) {
            synSQL += "and all_synonyms.OWNER =\'" + metadataConnection.getSchema() + "\'";
        } else if (table.eContainer() instanceof Schema) {
            Schema schema = (Schema) table.eContainer();
            synSQL += "and all_synonyms.OWNER =\'" + schema.getName() + "\'";
        }
        synSQL += " ORDER BY all_tab_columns.COLUMN_NAME"; //$NON-NLS-1$
        Statement sta = extractMeta.getConn().createStatement();
        extractMeta.setQueryStatementTimeout(sta);
        ResultSet columns = sta.executeQuery(synSQL);
        String typeName = null;
        int index = 0;
        List<String> columnLabels = new ArrayList<String>();
        try {
            while (columns.next()) {
                String columnName = columns.getString(GetColumn.COLUMN_NAME.name());
                TdColumn column = ColumnHelper.createTdColumn(columnName);

                String label = column.getLabel();
                label = ManagementTextUtils.filterSpecialChar(label);
                String label2 = label;
                final ICoreService coreService = getCoreService();
                if (coreService != null && coreService.isKeyword(label)) {
                    label = "_" + label; //$NON-NLS-1$
                }

                label = MetadataToolHelper.validateColumnName(label, index, columnLabels);
                column.setLabel(label);
                column.setOriginalField(label2);

                // no need for oracle
                // if (!ExtractMetaDataUtils.needFakeDatabaseMetaData(metadataConnection.getDbType(),
                // metadataConnection.isSqlMode())) {
                // dataType = columns.getInt(GetColumn.DATA_TYPE.name());
                typeName = columns.getString(GetColumn.DATA_TYPE.name());
                // }
                setLengthAndPrecision(column, columns, typeName);

                DatabaseConnection dbConnection = (DatabaseConnection) ConnectionHelper.getConnection(table);
                String dbmsId = dbConnection == null ? null : dbConnection.getDbmsId();
                if (dbmsId != null) {
                    MappingTypeRetriever mappingTypeRetriever = MetadataTalendType
                            .getMappingTypeRetriever(dbmsId);
                    String talendType = mappingTypeRetriever.getDefaultSelectedTalendType(typeName,
                            (int) column.getLength(), (int) column.getPrecision());
                    column.setTalendType(talendType);
                    String defaultSelectedDbType = MetadataTalendType
                            .getMappingTypeRetriever(dbConnection.getDbmsId())
                            .getDefaultSelectedDbType(talendType);
                    column.setSourceType(defaultSelectedDbType);
                }
                try {
                    column.setNullable("Y".equals(columns.getString(GetColumn.NULLABLE.name()))); //$NON-NLS-1$
                } catch (Exception e) {
                    log.error(e);
                }
                metadataColumns.add(column);
                columnLabels.add(column.getLabel());
                index++;

            }
        } finally {
            columns.close();
        }
    }

}

From source file:org.openbizview.util.Mailgrupos.java

/**
* Leer registros en la tabla//w w w  . j a  v  a 2 s  . c o  m
* @throws NamingException 
* @throws IOException 
**/
public void counter(Object filterValue) throws SQLException, NamingException {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);
        con = ds.getConnection();
        //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno
        DatabaseMetaData databaseMetaData = con.getMetaData();
        productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin

        String query = "";

        switch (productName) {
        case "Oracle":
            query = "SELECT count_mailgrupo('" + ((String) filterValue).toUpperCase() + "','" + instancia
                    + "') from dual";
            break;
        case "PostgreSQL":
            query = "SELECT count_mailgrupo('" + ((String) filterValue).toUpperCase() + "','" + instancia
                    + "')";
            break;
        case "Microsoft SQL Server":
            query = "SELECT DBO.count_mailgrupo('" + ((String) filterValue).toUpperCase() + "','" + instancia
                    + "')";
            break;
        }

        pstmt = con.prepareStatement(query);
        //System.out.println(query);

        r = pstmt.executeQuery();

        while (r.next()) {
            rows = r.getInt(1);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    //Cierra las conecciones
    pstmt.close();
    con.close();
    r.close();

}

From source file:org.apache.ode.scheduler.simple.jdbc.SchedulerDAOConnectionImpl.java

private Dialect guessDialect() {
    Dialect d = Dialect.UNKNOWN;//from   w  w w .ja  v  a  2 s .c  o  m
    Connection con = null;
    try {
        con = getConnection();
        DatabaseMetaData metaData = con.getMetaData();
        if (metaData != null) {
            String dbProductName = metaData.getDatabaseProductName();
            int dbMajorVer = metaData.getDatabaseMajorVersion();
            __log.debug("Using database " + dbProductName + " major version " + dbMajorVer);
            if (dbProductName.indexOf("DB2") >= 0) {
                d = Dialect.DB2;
            } else if (dbProductName.indexOf("Derby") >= 0) {
                d = Dialect.DERBY;
            } else if (dbProductName.indexOf("Firebird") >= 0) {
                d = Dialect.FIREBIRD;
            } else if (dbProductName.indexOf("HSQL") >= 0) {
                d = Dialect.HSQL;
            } else if (dbProductName.indexOf("Microsoft SQL") >= 0) {
                d = Dialect.SQLSERVER;
            } else if (dbProductName.indexOf("MySQL") >= 0) {
                d = Dialect.MYSQL;
            } else if (dbProductName.indexOf("Sybase") >= 0 || dbProductName.indexOf("ASE") >= 0
                    || dbProductName.indexOf("Adaptive") >= 0) {
                d = Dialect.SYBASE;
                if (dbMajorVer >= 12) {
                    d = Dialect.SYBASE12;
                }
            }
        }
    } catch (SQLException e) {
        __log.warn("Unable to determine database dialect", e);
    } finally {
        close(con);
    }
    __log.debug("Using database dialect: " + d);
    return d;
}

From source file:com.jaxio.celerio.configuration.database.support.MetadataExtractor.java

private DatabaseInfo extractDatabaseInfo(DatabaseMetaData databaseMetaData) {
    DatabaseInfo database = new DatabaseInfo();

    // database/* w w  w .  j a  v a2s. com*/
    try {
        database.setDatabaseProductName(databaseMetaData.getDatabaseProductName());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDatabaseProductVersion(databaseMetaData.getDatabaseProductVersion());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDatabaseMajorVersion(databaseMetaData.getDatabaseMajorVersion());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDatabaseMinorVersion(databaseMetaData.getDatabaseMinorVersion());
    } catch (Exception e) { /* ignore */
    }

    // driver
    try {
        database.setDriverName(databaseMetaData.getDriverName());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDriverVersion(databaseMetaData.getDriverVersion());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDriverMajorVersion(databaseMetaData.getDriverMajorVersion());
    } catch (Exception e) { /* ignore */
    }

    try {
        database.setDriverMinorVersion(databaseMetaData.getDriverMinorVersion());
    } catch (Exception e) { /* ignore */
    }

    return database;
}

From source file:org.enlacerh.util.Seg002.java

/**
* Leer registros en la tabla/*ww w  .ja v  a2  s .c  o m*/
* @throws NamingException 
* @throws IOException 
**/
public void counter(Object filterValue) throws SQLException, NamingException, IOException {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);

        con = ds.getConnection();
        //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno
        DatabaseMetaData databaseMetaData = con.getMetaData();
        productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin

        String query = null;

        switch (productName) {
        case "Oracle":
            query = "SELECT count_seg002(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).toUpperCase() + "') from dual";
            break;
        case "PostgreSQL":
            query = "SELECT count_seg002(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).toUpperCase() + "')";
            break;
        }

        pstmt = con.prepareStatement(query);
        //System.out.println(query);

        r = pstmt.executeQuery();

        while (r.next()) {
            rows = r.getInt(1);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    //Cierra las conecciones
    pstmt.close();
    con.close();
    r.close();

}

From source file:org.enlacerh.util.Seg001.java

/**
  * Leer registros en la tabla/*from w  ww .ja  v  a  2  s .  c om*/
  * @throws NamingException 
  * @throws IOException 
  **/
public void counter(Object filterValue) throws SQLException, NamingException, IOException {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);

        con = ds.getConnection();
        //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno
        DatabaseMetaData databaseMetaData = con.getMetaData();
        productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin

        String query = null;

        switch (productName) {
        case "Oracle":
            query = "SELECT count_seg001('" + ((String) filterValue).toUpperCase() + "') from dual";
            break;
        case "PostgreSQL":
            query = "SELECT count_seg001('" + ((String) filterValue).toUpperCase() + "')";
            break;
        }

        pstmt = con.prepareStatement(query);
        //System.out.println(query);

        r = pstmt.executeQuery();

        while (r.next()) {
            rows = r.getInt(1);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    //Cierra las conecciones
    pstmt.close();
    con.close();
    r.close();

}

From source file:nl.strohalm.cyclos.setup.DataBaseConfiguration.java

private void handleDatabase(final Properties properties) {
    // Retrieve the connection
    final String dataSource = StringUtils.trimToNull(properties.getProperty(Environment.DATASOURCE));
    Connection connection;//from   w  w w.j a v a2  s .  c  o  m
    String connectionLocation;
    if (dataSource != null) {
        // Use Hibernate's own DatasourceConnectionProvider when using a JNDI datasource
        final ConnectionProvider provider = new DatasourceConnectionProvider();
        provider.configure(properties);
        try {
            connection = provider.getConnection();
        } catch (final SQLException e) {
            final String msg = "Error connecting to datasource at " + dataSource;
            LOG.error(msg);
            throw new RuntimeException(msg, e);
        }
        connectionLocation = dataSource;
    } else {
        // Manually verify the connection
        final String driverClass = StringUtils.trimToNull(properties.getProperty(Environment.DRIVER));
        validateDriver(driverClass);
        final String url = properties.getProperty(Environment.URL);
        final String username = properties.getProperty(Environment.USER);
        final String password = properties.getProperty(Environment.PASS);
        connection = validateConnection(url, username, password);
        connectionLocation = url;
    }

    final JDBCWrapper jdbc = new JDBCWrapper(connection);

    // Check whether we will create the database if necessary
    final boolean embedded = Boolean.valueOf(properties.getProperty("cyclos.embedded.enable", "false"));

    // Get the connection meta data
    boolean dataBaseExists = true;
    String dataBaseName;
    String dataBaseVersion;
    try {
        final DatabaseMetaData metaData = connection.getMetaData();
        dataBaseName = metaData.getDatabaseProductName();
        dataBaseVersion = metaData.getDatabaseProductVersion();
    } catch (final SQLException e) {
        throw new RuntimeException("Error reading database metadata", e);
    }

    // Check if the database exists, by reading the current version
    final String currentVersion;
    try {
        currentVersion = readCurrentVersion(jdbc);
        if (currentVersion != null) {
            LOG.info(String.format("Cyclos database version %s found on %s version %s", currentVersion,
                    dataBaseName, dataBaseVersion));
        }
        dataBaseExists = currentVersion != null;
        // Check for new versions schema upgrade
        if (dataBaseExists) {
            final boolean autoUpgrade = Boolean
                    .valueOf(properties.getProperty("cyclos.autoSchemaUpgrade.enable", "false"));
            if (autoUpgrade) {
                // Run the schema upgrade
                final String newVersion = upgradeSchema(currentVersion, jdbc);
                if (!currentVersion.equals(newVersion)) {
                    // The version has changed. Add a custom property on the configuration properties for the cache
                    // manager to clear the current cache, because new entities may be incompatible with cached versions
                    properties.setProperty("cyclos.versionHasChanged", "true");
                }
            }
        } else {
            // For MySQL connections, we should ensure that the database is set to utf8
            if (embedded && dataBaseName.toLowerCase().equals("mysql")) {
                try {
                    jdbc.commit();
                    jdbc.execute("alter database character set utf8");
                } catch (final SQLException e) {
                    e.printStackTrace();
                    // Ignore
                }
            }
        }
    } finally {
        // Close the connection
        try {
            connection.close();
        } catch (final SQLException e) {
        }
    }

    // Run the setup if needed
    if (!dataBaseExists) {
        if (embedded) {
            final boolean smsEmbedded = Boolean
                    .valueOf(properties.getProperty("cyclos.embedded.sms.enable", "false"));
            LOG.info("Database is empty. Running setup to populate it");
            sessionFactory = configuration.buildSessionFactory();
            final Locale locale = LocaleConverter.instance()
                    .valueOf(properties.getProperty("cyclos.embedded.locale", "en_US"));
            final Setup setup = new Setup(configuration, sessionFactory);
            setup.setLocale(locale);
            setup.setCreateDataBase(true);
            setup.setCreateBasicData(true);
            setup.setCreateInitialData(true);
            setup.setCreateSmsData(smsEmbedded);
            setup.setForce(true);
            setup.execute();
        } else {
            throw new RuntimeException("Cyclos database not found at " + connectionLocation);
        }
    }
}

From source file:org.openbizview.util.Cst005.java

/**
 * Leer Datos de paises//from ww w .ja v  a2 s. co  m
 * @throws NamingException 
* @throws IOException 
 **/
public void select(int first, int pageSize, String sortField, Object filterValue)
        throws SQLException, ClassNotFoundException, NamingException {

    //System.out.println("entre al metodo SELECT");   
    Context initContext = new InitialContext();
    DataSource ds = (DataSource) initContext.lookup(JNDI);
    con = ds.getConnection();
    //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno
    DatabaseMetaData databaseMetaData = con.getMetaData();
    productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin

    //Consulta paginada
    String query = "SELECT * FROM";
    query += "(select query.*, rownum as rn from";
    query += "(SELECT A.CENTRO, A.ORDEN, B.DESCR AS DESC1, C.DESCR AS DESC2 ";
    query += " FROM CST005 A, CST001 B, CST002 C";
    query += " WHERE A.CENTRO = B.CODIGO";
    query += " AND A.ORDEN = C.CODIGO";
    query += " GROUP BY A.CENTRO, A.ORDEN, B.DESCR, C.DESCR";
    query += ")query ) ";
    query += " WHERE ROWNUM <=" + pageSize;
    query += " AND rn > (" + first + ")";
    query += " ORDER BY  CENTRO, ORDEN ";

    pstmt = con.prepareStatement(query);
    //System.out.println(query);

    r = pstmt.executeQuery();

    while (r.next()) {
        Cst005 select = new Cst005();
        select.setZceno(r.getString(1));
        select.setZordf(r.getString(2));
        select.setZdesc1(r.getString(1) + " - " + r.getString(3));
        select.setZdesc2(r.getString(2) + " - " + r.getString(4));
        select.setZdesc3(r.getString(3));
        select.setZdesc4(r.getString(4));
        //Agrega la lista
        list.add(select);
    }
    //Cierra las conecciones
    pstmt.close();
    con.close();

}

From source file:org.enlacerh.util.Pnt003.java

/**
* Leer registros en la tabla/*from w w  w  .j  a v  a 2 s .com*/
* @throws NamingException 
* @throws IOException 
**/
public void counter(Object filterValue) throws SQLException, NamingException {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);

        String query = null;

        con = ds.getConnection();
        //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno
        DatabaseMetaData databaseMetaData = con.getMetaData();
        productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin

        switch (productName) {
        case "Oracle":
            query = "SELECT count_pnt003(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).toUpperCase() + "') from dual";
            break;
        case "PostgreSQL":
            query = "SELECT count_pnt003(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).toUpperCase() + "')";
            break;
        }

        pstmt = con.prepareStatement(query);
        //System.out.println(query);

        r = pstmt.executeQuery();

        while (r.next()) {
            rows = r.getInt(1);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    //Cierra las conecciones
    pstmt.close();
    con.close();
    r.close();

}