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:uap.workflow.engine.cfg.ProcessEngineConfigurationImpl.java

public void initDatabaseType() {
    Connection connection = null;
    try {/*from   www. j  a  v  a2  s . co  m*/
        connection = dataSource.getConnection();
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String databaseProductName = databaseMetaData.getDatabaseProductName();
        log.fine("database product name: '" + databaseProductName + "'");
        databaseType = databaseTypeMappings.getProperty(databaseProductName);
        if (databaseType == null) {
            throw new WorkflowException(
                    "couldn't deduct database type from database product name '" + databaseProductName + "'");
        }
        log.fine("using database type: " + databaseType);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.hydromatic.optiq.test.JdbcTest.java

/**
 * Make sure that the properties look sane.
 *///from  w  w w .j a  va2s .c om
@Test
public void testVersion() throws ClassNotFoundException, SQLException {
    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:optiq:");
    OptiqConnection optiqConnection = connection.unwrap(OptiqConnection.class);
    final DatabaseMetaData metaData = optiqConnection.getMetaData();
    assertEquals("Optiq JDBC Driver", metaData.getDriverName());

    final String driverVersion = metaData.getDriverVersion();
    final int driverMajorVersion = metaData.getDriverMajorVersion();
    final int driverMinorVersion = metaData.getDriverMinorVersion();
    assertEquals(0, driverMajorVersion);
    assertEquals(4, driverMinorVersion);

    assertEquals("Optiq", metaData.getDatabaseProductName());
    final String databaseProductVersion = metaData.getDatabaseProductVersion();
    final int databaseMajorVersion = metaData.getDatabaseMajorVersion();
    assertEquals(driverMajorVersion, databaseMajorVersion);
    final int databaseMinorVersion = metaData.getDatabaseMinorVersion();
    assertEquals(driverMinorVersion, databaseMinorVersion);

    // Check how version is composed of major and minor version. Note that
    // version is stored in pom.xml; major and minor version are
    // stored in net-hydromatic-optiq-jdbc.properties.
    if (!driverVersion.endsWith("-SNAPSHOT")) {
        assertTrue(driverVersion.startsWith("0."));
        String[] split = driverVersion.split("\\.");
        assertTrue(split.length >= 2);
        assertTrue(driverVersion.startsWith(driverMajorVersion + "." + driverMinorVersion + "."));
    }
    if (!databaseProductVersion.endsWith("-SNAPSHOT")) {
        assertTrue(databaseProductVersion.startsWith("0."));
        String[] split = databaseProductVersion.split("\\.");
        assertTrue(split.length >= 2);
        assertTrue(databaseProductVersion.startsWith(databaseMajorVersion + "." + databaseMinorVersion + "."));
    }

    connection.close();
}

From source file:org.dbist.dml.impl.DmlJdbc.java

@SuppressWarnings("unchecked")
@Override/*w  w  w . ja v  a2s  .c  o  m*/
public void afterPropertiesSet() throws Exception {
    boolean debug = logger.isDebugEnabled();
    super.afterPropertiesSet();
    ValueUtils.assertNotEmpty("domain", getDomain());
    ValueUtils.assertNotEmpty("dataSource", getDataSource());
    ValueUtils.assertNotEmpty("jdbcOperations", getJdbcOperations());
    ValueUtils.assertNotEmpty("namedParameterJdbcOperations", getNamedParameterJdbcOperations());

    if (ValueUtils.isEmpty(getDbType())) {
        DatabaseMetaData metadata = dataSource.getConnection().getMetaData();
        setDbType(metadata.getDatabaseProductName().toLowerCase());
        if (getDbType().startsWith("microsoft sql server")) {
            setDbType("sqlserver");
        } else if (getDbType().startsWith("db2/")) {
            setDbType("db2");
        }
    }
    if (getQueryMapper() == null) {
        if (getDbType().equals("mysql"))
            setQueryMapper(new QueryMapperMysql());
        else if (getDbType().equals("postgresql"))
            setQueryMapper(new QueryMapperPostgresql());
        else if (getDbType().equals("oracle"))
            setQueryMapper(new QueryMapperOracle());
        else if (getDbType().equals("db2"))
            setQueryMapper(new QueryMapperDb2());
        else if (getDbType().equals("sqlserver"))
            setQueryMapper(new QueryMapperSqlserver());
    }
    if (!isSupported())
        throw new IllegalArgumentException("Unsupported dbType: " + getDbType());

    if ("sqlserver".equals(getDbType())) {
        List<String> domainList = new ArrayList<String>(this.domainList.size());
        for (String domain : this.domainList) {
            if (domain.indexOf('.') != -1)
                continue;
            domainList.add(domain + ".dbo");
        }
        this.domainList = domainList;
    }

    if (ValueUtils.isEmpty(columnAliasRuleForMapKey))
        columnAliasRuleForMapKey = COLUMNALIASRULE_DEFAULT;
    else if (!COLUMNALIASRULE_LIST.contains(columnAliasRuleForMapKey))
        throw new IllegalArgumentException("Unsupported columnAliasRule: ");
    columnAliasRule = COLUMNALIASRULE_LIST.indexOf(columnAliasRuleForMapKey);

    if (maxSqlByPathCacheSize > 0)
        sqlByPathCache = Collections.synchronizedMap(new LRUMap(maxSqlByPathCacheSize));
    if (debug)
        logger.debug("dml loaded (dbType: " + getDbType() + ")");
}

From source file:ru.codeinside.adm.AdminServiceImpl.java

/**
 * ?? ??  ? userTask  ?.// ww  w .  j a  va2  s  . c om
 */
private void fixAssignmentHistory(final Connection connection) {

    try {
        final DatabaseMetaData metaData = connection.getMetaData();
        if ("H2".equals(metaData.getDatabaseProductName())) {
            return; // , SQL  ?? ? H2
        }

        final Statement s = connection.createStatement();

        final boolean hasFix;
        {
            final ResultSet rs = s
                    .executeQuery("select value_ from act_ge_property where name_ = 'assignFixed'");
            hasFix = rs.next();
            rs.close();
        }

        if (!hasFix) {
            s.execute("create temp table fix (" + " bid bigint not null," + " assignee varchar(64) not null"
                    + ") on commit drop");
            s.execute("insert into fix select distinct b.id, h.assignee_ from act_hi_taskinst h, bid b"
                    + " where b.processinstanceid = h.proc_inst_id_ and h.assignee_ is not null");
            s.execute(
                    "delete from fix using bidworkers where bid=bidworkers.bid_id and assignee=bidworkers.employee_login");
            s.execute("insert into bidworkers select bid, assignee from fix");
            s.execute("insert into act_ge_property values ('assignFixed', '1', 0)");
        }
        s.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java

public ContentSourceSpecs init(WGDatabase db, String path) throws WGInvalidDatabaseException {

    Map creationOptions = db.getCreationOptions();

    // Try to get shared connection pool from server
    boolean useSharedPool = WGUtils.getBooleanMapValue(db.getCreationOptions(), WGDatabase.COPTION_SHAREDPOOL,
            true);/*from  w  w w .j  a  v  a  2  s  . c  o m*/
    if (useSharedPool && db.getCreationOptions().containsKey(Database.OPTION_PATH)
            && db.getServer() instanceof SharedPoolJDBCDatabaseServer) {
        SharedPoolJDBCDatabaseServer poolServer = (SharedPoolJDBCDatabaseServer) db.getServer();
        if (poolServer.isPoolAvailable(new CSVersion(0, 0))) {
            try {
                _connProvider = poolServer.createPoolConnectionProvider(
                        (String) db.getCreationOptions().get(Database.OPTION_PATH));
                WGFactory.getLogger()
                        .info("Database '" + db.getDbReference()
                                + "' uses the shared connection pool of database server '"
                                + db.getServer().getTitle(Locale.getDefault()) + "'");
            } catch (WGInvalidDatabaseException e) {
                throw e;
            } catch (Exception e) {
                throw new WGInvalidDatabaseException("Exception connecting to shared database server pool", e);
            }
        }
    }

    // Create regular pool
    if (_connProvider == null) {
        // Default JDBC props
        Properties props = new Properties();
        props.put("autocommit", "true");

        // Gather configured JDBC props
        Iterator optsIt = creationOptions.keySet().iterator();
        while (optsIt.hasNext()) {
            String option = (String) optsIt.next();
            if (option.startsWith(("jdbc."))) {
                props.put(option.substring(5), creationOptions.get(option));
            }
        }

        // Set login props
        if (db.getMasterLoginName() != null && !db.getMasterLoginName().equals("")) {
            props.put("user", db.getMasterLoginName());
            if (db.getMasterLoginPassword() != null) {
                props.put("password", db.getMasterLoginPassword());
            }
        }

        // Set dbkey property so we see DBCP metrics via JMX
        props.put("dbcp.dbkey", db.getDbReference());

        // Build JDBC Connection Creator
        try {
            _connProvider = new JDBCConnectionProvider(path,
                    (String) db.getCreationOptions().get(COPTION_DRIVER), props, true);
        } catch (JDBCConnectionException e3) {
            throw new WGInvalidDatabaseException("Exception setting up JDBC connection", e3);
        }
    }

    // Gather other options
    try {
        if (creationOptions.containsKey("ResultSetType")) {
            _resultSetType = Integer.parseInt((String) creationOptions.get("ResultSetType"));
        }
    } catch (NumberFormatException e2) {
        throw new WGInvalidDatabaseException(
                "Cannot parse db option 'ResultSetType' as integer: " + _resultSetType);
    }

    // Gather meta data
    try {
        Connection connection = getConnection();
        if (connection == null) {
            throw new WGInvalidDatabaseException("Unable to get connection");
        }

        DatabaseMetaData dbMeta = connection.getMetaData();
        ResultSet resultSet = dbMeta.getTables(null, null, null,
                new String[] { "TABLE", "VIEW", "GLOBAL TEMPORARY", "LOCAL TEMPORARY" });
        startResultSet(resultSet);
        while (resultSet.next()) {

            TableName tableName = new TableName(resultSet);
            ResultSet keyResultSet = dbMeta.getPrimaryKeys(tableName.getCatalog(), tableName.getSchema(),
                    tableName.getName());
            List keyColumns = new ArrayList();
            startResultSet(keyResultSet);
            while (keyResultSet.next()) {
                keyColumns.add(keyResultSet.getString("COLUMN_NAME").toLowerCase());
            }

            if (keyColumns.size() > 0) {
                _tables.put(tableName.getCompleteName().toLowerCase(), keyColumns);
            }
            keyResultSet.close();

        }
        resultSet.close();

        _server = dbMeta.getDatabaseProductName() + " Version " + dbMeta.getDatabaseProductVersion();
        _title = _server;
    } catch (SQLException e) {
        throw new WGInvalidDatabaseException(
                "SQL Error building connection to path " + path + ": " + e.getMessage());
    }

    // Last changed update process
    int refreshSeconds = 60;
    if (creationOptions.containsKey(COPTION_REFRESH)) {
        try {
            refreshSeconds = Integer.parseInt((String) creationOptions.get(COPTION_REFRESH));
        } catch (NumberFormatException e1) {
            Logger.getLogger(LOGGER_NAME).error("Cannot parse option " + COPTION_REFRESH + " as integer: "
                    + creationOptions.get(COPTION_REFRESH));
        }
    }

    // Gather specs
    ContentSourceSpecs specs = new ContentSourceSpecs();
    specs.setBrowseable(true);
    specs.setWritable(true);
    specs.setCalculatesKeys(true);
    specs.setMaintainsLastChanged(false);
    specs.setLowerCaseItems(true);
    specs.setServePropertiesAsMetas(false);
    specs.setContentReadProtected(false);
    return specs;

}

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

/**
 * get Table Comment./*from www.  ja  v  a2  s . c om*/
 * 
 * @param dbJDBCMetadata
 * @param tables
 * @param tableName
 * @param catalogName
 * @param schemaPattern
 * @return
 */
private String getTableComment(DatabaseMetaData dbJDBCMetadata, ResultSet tables, String tableName,
        String catalogName, String schemaPattern) {
    String tableComment = getStringFromResultSet(tables, GetTable.REMARKS.name());
    try {
        String productName = dbJDBCMetadata.getDatabaseProductName();
        if (StringUtils.isBlank(tableComment)) {
            String selectRemarkOnTable = MetadataConnectionUtils.getCommentQueryStr(productName, tableName,
                    catalogName, schemaPattern);
            if (selectRemarkOnTable != null) {
                tableComment = executeGetCommentStatement(selectRemarkOnTable, dbJDBCMetadata.getConnection());
            }
        }
    } catch (SQLException e) {
        log.error(e, e);
    }
    return tableComment;
}

From source file:org.springframework.jdbc.core.JdbcTemplateTests.java

public void testBatchUpdate() throws Exception {
    final String[] sql = { "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1",
            "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 2" };

    MockControl ctrlStatement = MockControl.createControl(Statement.class);
    Statement mockStatement = (Statement) ctrlStatement.getMock();
    mockStatement.getConnection();/*from  w  w w .j  av a 2s.  c  o m*/
    ctrlStatement.setReturnValue(mockConnection);
    mockStatement.addBatch(sql[0]);
    ctrlStatement.setVoidCallable();
    mockStatement.addBatch(sql[1]);
    ctrlStatement.setVoidCallable();
    mockStatement.executeBatch();
    ctrlStatement.setReturnValue(new int[] { 1, 1 });
    if (debugEnabled) {
        mockStatement.getWarnings();
        ctrlStatement.setReturnValue(null);
    }
    mockStatement.close();
    ctrlStatement.setVoidCallable();

    MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
    DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
    mockDatabaseMetaData.getDatabaseProductName();
    ctrlDatabaseMetaData.setReturnValue("MySQL");
    mockDatabaseMetaData.supportsBatchUpdates();
    ctrlDatabaseMetaData.setReturnValue(true);

    mockConnection.getMetaData();
    ctrlConnection.setReturnValue(mockDatabaseMetaData, 2);
    mockConnection.createStatement();
    ctrlConnection.setReturnValue(mockStatement);

    ctrlStatement.replay();
    ctrlDatabaseMetaData.replay();
    replay();

    JdbcTemplate template = new JdbcTemplate(mockDataSource, false);

    int[] actualRowsAffected = template.batchUpdate(sql);
    assertTrue("executed 2 updates", actualRowsAffected.length == 2);

    ctrlStatement.verify();
    ctrlDatabaseMetaData.verify();
}

From source file:org.springframework.jdbc.core.JdbcTemplateTests.java

public void testBatchUpdateWithNoBatchSupportAndSelect() throws Exception {
    final String[] sql = { "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1",
            "SELECT * FROM NOSUCHTABLE" };

    MockControl ctrlStatement = MockControl.createControl(Statement.class);
    Statement mockStatement = (Statement) ctrlStatement.getMock();
    mockStatement.getConnection();//from  w w  w. ja v  a2s  .co m
    ctrlStatement.setReturnValue(mockConnection);
    mockStatement.execute(sql[0]);
    ctrlStatement.setReturnValue(false);
    mockStatement.getUpdateCount();
    ctrlStatement.setReturnValue(1);
    mockStatement.execute(sql[1]);
    ctrlStatement.setReturnValue(true);
    mockStatement.close();
    ctrlStatement.setVoidCallable();

    MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
    DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
    mockDatabaseMetaData.getDatabaseProductName();
    ctrlDatabaseMetaData.setReturnValue("MySQL");
    mockDatabaseMetaData.supportsBatchUpdates();
    ctrlDatabaseMetaData.setReturnValue(false);

    mockConnection.getMetaData();
    ctrlConnection.setReturnValue(mockDatabaseMetaData, 2);
    mockConnection.createStatement();
    ctrlConnection.setReturnValue(mockStatement);

    ctrlStatement.replay();
    ctrlDatabaseMetaData.replay();
    replay();

    JdbcTemplate template = new JdbcTemplate(mockDataSource, false);

    try {
        template.batchUpdate(sql);
        fail("Shouldn't have executed batch statement with a select");
    } catch (DataAccessException ex) {
        // pass
        assertTrue("Check exception type", ex.getClass() == InvalidDataAccessApiUsageException.class);
    }

    ctrlStatement.verify();
    ctrlDatabaseMetaData.verify();
}

From source file:org.springframework.jdbc.core.JdbcTemplateTests.java

public void testBatchUpdateWithNoBatchSupport() throws Exception {
    final String[] sql = { "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1",
            "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 2" };

    MockControl ctrlStatement = MockControl.createControl(Statement.class);
    Statement mockStatement = (Statement) ctrlStatement.getMock();
    mockStatement.getConnection();//from  ww  w. j a v  a  2 s.c o m
    ctrlStatement.setReturnValue(mockConnection);
    mockStatement.execute(sql[0]);
    ctrlStatement.setReturnValue(false);
    mockStatement.getUpdateCount();
    ctrlStatement.setReturnValue(1);
    mockStatement.execute(sql[1]);
    ctrlStatement.setReturnValue(false);
    mockStatement.getUpdateCount();
    ctrlStatement.setReturnValue(1);
    if (debugEnabled) {
        mockStatement.getWarnings();
        ctrlStatement.setReturnValue(null);
    }
    mockStatement.close();
    ctrlStatement.setVoidCallable();

    MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
    DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
    mockDatabaseMetaData.getDatabaseProductName();
    ctrlDatabaseMetaData.setReturnValue("MySQL");
    mockDatabaseMetaData.supportsBatchUpdates();
    ctrlDatabaseMetaData.setReturnValue(false);

    mockConnection.getMetaData();
    ctrlConnection.setReturnValue(mockDatabaseMetaData, 2);
    mockConnection.createStatement();
    ctrlConnection.setReturnValue(mockStatement);

    ctrlStatement.replay();
    ctrlDatabaseMetaData.replay();
    replay();

    JdbcTemplate template = new JdbcTemplate(mockDataSource, false);

    int[] actualRowsAffected = template.batchUpdate(sql);
    assertTrue("executed 2 updates", actualRowsAffected.length == 2);

    ctrlStatement.verify();
    ctrlDatabaseMetaData.verify();
}

From source file:org.springframework.jdbc.core.JdbcTemplateTests.java

public void testSQLErrorCodeTranslation() throws Exception {
    final SQLException sex = new SQLException("I have a known problem", "99999", 1054);
    final String sql = "SELECT ID FROM CUSTOMER";

    MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
    ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
    mockResultSet.next();/*www . j a v a 2 s  . c  om*/
    ctrlResultSet.setReturnValue(true);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class);
    PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock();
    mockStatement.executeQuery(sql);
    ctrlStatement.setReturnValue(mockResultSet);
    mockStatement.close();
    ctrlStatement.setVoidCallable();

    MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
    DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
    mockDatabaseMetaData.getDatabaseProductName();
    ctrlDatabaseMetaData.setReturnValue("MySQL");

    mockConnection.createStatement();
    ctrlConnection.setReturnValue(mockStatement);
    mockConnection.getMetaData();
    ctrlConnection.setReturnValue(mockDatabaseMetaData);

    ctrlResultSet.replay();
    ctrlStatement.replay();
    ctrlDatabaseMetaData.replay();
    replay();

    JdbcTemplate template = new JdbcTemplate(mockDataSource);
    try {
        template.query(sql, new RowCallbackHandler() {
            public void processRow(ResultSet rs) throws SQLException {
                throw sex;
            }
        });
        fail("Should have thrown BadSqlGrammarException");
    } catch (BadSqlGrammarException ex) {
        // expected
        assertTrue("Wanted same exception back, not " + ex, sex == ex.getCause());
    }

    ctrlResultSet.verify();
    ctrlStatement.verify();
    ctrlDatabaseMetaData.verify();
}