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:com.alibaba.otter.canal.example.db.dialect.AbstractDbDialect.java

public AbstractDbDialect(final JdbcTemplate jdbcTemplate, LobHandler lobHandler) {
    this.jdbcTemplate = jdbcTemplate;
    this.lobHandler = lobHandler;
    // ?transction
    this.transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    // ??/*from  w  w w . j  a v  a  2  s .co  m*/
    jdbcTemplate.execute(new ConnectionCallback() {

        public Object doInConnection(Connection c) throws SQLException, DataAccessException {
            DatabaseMetaData meta = c.getMetaData();
            databaseName = meta.getDatabaseProductName();
            databaseMajorVersion = meta.getDatabaseMajorVersion();
            databaseMinorVersion = meta.getDatabaseMinorVersion();

            return null;
        }
    });

    initTables(jdbcTemplate);
}

From source file:org.apache.hadoop.hive.jdbchandler.HiveDBOutputFormat.java

@Override
public RecordWriter getHiveRecordWriter(JobConf job, Path finalOutPath, Class<? extends Writable> valueClass,
        boolean isCompressed, Properties tableProperties, Progressable progress) throws IOException {
    // TODO Auto-generated method stub
    DBConfiguration dbConf = new DBConfiguration(job);
    String tableName = dbConf.getOutputTableName();
    String[] fieldNames = dbConf.getOutputFieldNames();
    boolean truncate = dbConf.getTruncateBeforeInsert();
    boolean replace = dbConf.getOutputReplace();
    int batchSize = dbConf.getBatchExecuteSize();
    Connection connection = null;

    try {/*  w  w  w .  j  a v  a 2  s  . co  m*/
        connection = new DBManager(dbConf.getConf()).getConnection();
        DatabaseMetaData dbMeta = connection.getMetaData();
        String dbProductName = dbMeta.getDatabaseProductName().toUpperCase();

        // use database product name to determine appropriate record writer.
        if (dbProductName.startsWith("ORACLE")) {
            // use Oracle-specific db writer.
            return new OracleDBRecordWriter(connection, tableName, fieldNames, truncate, replace, batchSize);
        } else if (dbProductName.startsWith("MYSQL")) {
            // use MySQL-specific db writer.
            return new MySQLDBRecordWriter(connection, tableName, fieldNames, truncate, replace, batchSize);
        } else if (dbProductName.startsWith("POSTGRESQL")) {
            // use PostgreSQL-specific db writer.
            return new PostgresDBRecordWriter(connection, tableName, fieldNames, truncate, replace, batchSize);
        } else {
            // Generic writer.
            return new DBRecordWriter(connection, tableName, fieldNames, truncate, replace, batchSize);
        }

    } catch (SQLException e) {
        LOG.error(StringUtils.stringifyException(e));
        throw new IOException(StringUtils.stringifyException(e));
    }

}

From source file:org.apache.kylin.common.persistence.JDBCConnectionManager.java

private JDBCConnectionManager(KylinConfig config) {
    try {//www  . j  av a 2 s. c  om
        this.dbcpProps = initDbcpProps(config);

        dataSource = BasicDataSourceFactory.createDataSource(getDbcpProperties());
        Connection conn = getConn();
        DatabaseMetaData mdm = conn.getMetaData();
        logger.info("Connected to {0} {1}", mdm.getDatabaseProductName(), mdm.getDatabaseProductVersion());
        closeQuietly(conn);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.tec.webapp.jdbc.service.impl.SystemSvcImpl.java

/**
 * {@inheritDoc}/* w ww. j  ava2  s.  c  o  m*/
 */
@Override()
public SerializableList<StatusBean> getStatus() {
    Connection conn = null;
    try {
        SerializableList<StatusBean> slist = new SerializableList<StatusBean>();

        // get java information
        slist.add(new StatusBean("java.version", System.getProperty("java.version")));

        //get Servlet information
        slist.add(new StatusBean("server.info", mServletContext.getServerInfo()));

        StringBuilder buff = new StringBuilder();

        buff.append(mServletContext.getMajorVersion());
        buff.append('.');
        buff.append(mServletContext.getMinorVersion());

        slist.add(new StatusBean("servlet.version", buff.toString()));

        // get database information
        conn = mDataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        slist.add(new StatusBean("database.server", dmd.getDatabaseProductName()));
        slist.add(new StatusBean("database.version", dmd.getDatabaseProductVersion()));
        slist.add(new StatusBean("jdbc.driver", dmd.getDriverName()));
        slist.add(new StatusBean("jdbc.driver.version", dmd.getDriverVersion()));

        // spring
        slist.add(new StatusBean("spring.version", SpringVersion.getVersion()));

        return slist;
    } catch (Throwable e) {
        throw new RuntimeException("failed to get system status", e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Throwable e) {
                mLogger.error("failed to get system status", e);
            }
        }
    }
}

From source file:org.sonar.server.platform.monitoring.DatabaseMonitor.java

private void completeDbAttributes(Map<String, Object> attributes) {
    try (DbSession dbSession = dbClient.openSession(false); Connection connection = dbSession.getConnection()) {
        DatabaseMetaData metadata = connection.getMetaData();
        attributes.put("Database", metadata.getDatabaseProductName());
        attributes.put("Database Version", metadata.getDatabaseProductVersion());
        attributes.put("Username", metadata.getUserName());
        attributes.put("URL", metadata.getURL());
        attributes.put("Driver", metadata.getDriverName());
        attributes.put("Driver Version", metadata.getDriverVersion());
        attributes.put("Version Status", getMigrationStatus());
    } catch (SQLException e) {
        throw new IllegalStateException("Fail to get DB metadata", e);
    }/*from w ww  .  j a v  a 2 s .c  o m*/
}

From source file:com.tera.common.database.factory.AbstractDatabaseFactory.java

/**
 * @param dbConfig//from   w  ww . ja va 2 s . c  o  m
 * @throws Error
 */
void createConnectionPool(DatabaseConfiguration dbConfig) throws Error {
    log.info("Creating DB pool");
    connectionPool = new GenericObjectPool();
    connectionPool.setMaxIdle(dbConfig.getConnectionsIdelMax());
    connectionPool.setMinIdle(dbConfig.getConnectionsIdleMin());
    connectionPool.setMaxActive(dbConfig.getConnectionsActiveMax());
    connectionPool.setTestOnBorrow(true);

    try {
        dataSource = setupDataSource(dbConfig);
        Connection c = getConnection();
        DatabaseMetaData dmd = c.getMetaData();
        databaseName = dmd.getDatabaseProductName();
        databaseMajorVersion = dmd.getDatabaseMajorVersion();
        databaseMinorVersion = dmd.getDatabaseMinorVersion();
        c.close();
    } catch (Exception e) {
        log.error("Error with connection string: {}", dbConfig, e);
        throw new Error("DatabaseFactory not initialized!");
    }
    log.info("Successfully connected to the database");
}

From source file:org.phenotips.pingback.internal.client.data.DatabasePingDataProviderTest.java

@Test
public void provideData() throws Exception {
    Execution execution = this.mocker.getInstance(Execution.class);
    ExecutionContext executionContext = mock(ExecutionContext.class);
    when(execution.getContext()).thenReturn(executionContext);
    XWikiContext xwikiContext = mock(XWikiContext.class);
    when(executionContext.getProperty(XWikiContext.EXECUTIONCONTEXT_KEY)).thenReturn(xwikiContext);
    com.xpn.xwiki.XWiki xwiki = mock(com.xpn.xwiki.XWiki.class);
    when(xwikiContext.getWiki()).thenReturn(xwiki);
    XWikiCacheStoreInterface cacheStore = mock(XWikiCacheStoreInterface.class);
    when(xwiki.getStore()).thenReturn(cacheStore);
    XWikiHibernateStore store = mock(XWikiHibernateStore.class);
    when(cacheStore.getStore()).thenReturn(store);
    DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class);
    when(store.getDatabaseMetaData()).thenReturn(databaseMetaData);
    when(databaseMetaData.getDatabaseProductName()).thenReturn("HSQL Database Engine");
    when(databaseMetaData.getDatabaseProductVersion()).thenReturn("2.2.9");

    JSONAssert.assertEquals("{\"dbName\":\"HSQL Database Engine\",\"dbVersion\":\"2.2.9\"}",
            new JSONObject(this.mocker.getComponentUnderTest().provideData()), false);
}

From source file:org.alfresco.repo.domain.schema.DataSourceCheck.java

public void init() {
    logger.info(I18NUtil.getMessage(MSG_DB_CONNECTION, dbUrl, dbUsername));

    Connection con = null;//w w w  .  j  a  v  a  2  s.c  o  m
    try {
        con = dataSource.getConnection();
        con.setAutoCommit(true);
        DatabaseMetaData meta = con.getMetaData();
        logger.info(I18NUtil.getMessage(MSG_DB_VERSION, meta.getDatabaseProductName(),
                meta.getDatabaseProductVersion()));

        Dialect dialect = DialectFactory.buildDialect(cfg.getProperties(), meta.getDatabaseProductName(),
                meta.getDatabaseMajorVersion());

        // Check MS SQL Server specific settings
        if (dialect instanceof SQLServerDialect) {
            if (transactionIsolation != SQL_SERVER_TRANSACTION_ISOLATION) {
                throw new AlfrescoRuntimeException(ERR_WRONG_TRANSACTION_ISOLATION_SQL_SERVER,
                        new Object[] { transactionIsolation, SQL_SERVER_TRANSACTION_ISOLATION });
            }
        }
    } catch (RuntimeException re) {
        // just rethrow
        throw re;
    } catch (Exception e) {
        throw new AlfrescoRuntimeException(ERR_DB_CONNECTION, new Object[] { e.getMessage() }, e);
    } finally {
        try {
            con.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.tec.webapp.orm.service.impl.SystemSvcImpl.java

/**
 * {@inheritDoc}//ww  w  .  j  a v  a2 s .c o  m
 */
@Override()
public SerializableList<StatusBean> getStatus() {
    Connection conn = null;
    try {
        SerializableList<StatusBean> slist = new SerializableList<StatusBean>();

        // get java information
        slist.add(new StatusBean("java.version", System.getProperty("java.version")));

        //get Servlet information
        slist.add(new StatusBean("server.info", mServletContext.getServerInfo()));

        StringBuilder buff = new StringBuilder();

        buff.append(mServletContext.getMajorVersion());
        buff.append('.');
        buff.append(mServletContext.getMinorVersion());

        slist.add(new StatusBean("servlet.version", buff.toString()));

        // get database information
        conn = mDataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        slist.add(new StatusBean("database.server", dmd.getDatabaseProductName()));
        slist.add(new StatusBean("database.version", dmd.getDatabaseProductVersion()));
        slist.add(new StatusBean("jdbc.driver", dmd.getDriverName()));
        slist.add(new StatusBean("jdbc.driver.version", dmd.getDriverVersion()));

        // spring
        slist.add(new StatusBean("spring.version", SpringVersion.getVersion()));

        // hibernate
        slist.add(new StatusBean("hibernate.version", Version.getVersionString()));
        slist.add(new StatusBean("hibernate.session.factory", mSessionFactory.getClass().getName()));

        return slist;
    } catch (Throwable e) {
        throw new RuntimeException("failed to get system status", e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Throwable e) {
                mLogger.error("failed to get system status", e);
            }
        }
    }
}

From source file:org.obiba.runtime.upgrade.support.DatabaseMetadataUtil.java

/**
 * Returns the database product name.//from  ww  w. j a v a 2s  . c  om
 *
 * @return database product name
 */
public String getDatabaseProductName() {
    String databaseProductName;
    try {
        databaseProductName = (String) JdbcUtils.extractDatabaseMetaData(dataSource,
                new DatabaseMetaDataCallback() {
                    @Override
                    public Object processMetaData(DatabaseMetaData dbmd)
                            throws SQLException, MetaDataAccessException {
                        return dbmd.getDatabaseProductName();
                    }
                });
    } catch (MetaDataAccessException e) {
        throw new RuntimeException(e);
    }

    return databaseProductName;
}