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.kawanfw.test.api.client.ArrayTest.java

/**
 * @param connection/*from  w w w  .  ja v  a 2s.  co m*/
 *            the AceQL Connection
 * 
 * @throws SQLException
 * @throws Exception
 */
public void test(Connection connection) throws SQLException, Exception {

    MessageDisplayer.initClassDisplay(this.getClass().getSimpleName());

    DatabaseMetaData databaseMetaData = connection.getMetaData();
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductName()   : " + databaseMetaData.getDatabaseProductName());

    if (connection instanceof RemoteConnection) {
        RemoteConnection connectionHttp = (RemoteConnection) connection;
        if (connectionHttp.isStatelessMode()) {
            MessageDisplayer.display("Arrays are not supported in stateless mode");
            return;
        }
    }

    if (!new SqlUtil(connection).isPostgreSQL() && !new SqlUtil(connection).isHSQLDB()
            && !new SqlUtil(connection).isOracle()) {
        MessageDisplayer.display("Arrays tests are only supported in HSQLDB, Oracle Database & PostgreSQL");
        return;
    }

    Object[] northEastRegion = { "10022", "02110", "07399" };

    String sql = null;
    boolean doInsert = true;

    if (doInsert) {

        // Array aArray = connection.createArrayOf("varchar",
        // northEastRegion);

        Array aArray = null;

        if (new SqlUtil(connection).isOracle()) {
            aArray = connection.createArrayOf("VCARRAY", northEastRegion);
        } else {
            aArray = connection.createArrayOf("varchar", northEastRegion);
        }

        PreparedStatement pstmt = connection.prepareStatement("delete from REGIONS where region_name = ?");
        pstmt.setString(1, "NorthEast");
        pstmt.executeUpdate();
        pstmt.close();

        PreparedStatement pstmt2 = connection
                .prepareStatement("insert into REGIONS (region_name, zips) " + "VALUES (?, ?)");
        pstmt2.setString(1, "NorthEast");
        pstmt2.setArray(2, aArray);
        pstmt2.executeUpdate();
        pstmt2.close();

    }

    sql = "select * from REGIONS";
    PreparedStatement prepStatement = connection.prepareStatement(sql);
    ResultSet rs = prepStatement.executeQuery();

    while (rs.next()) {
        String region_name = rs.getString(1);
        MessageDisplayer.display(region_name + "  ");

        Array z = rs.getArray("ZIPS");

        Object[] zips = (Object[]) z.getArray();

        for (int i = 0; i < zips.length; i++) {
            System.out.print(zips[i] + " ");
        }
        MessageDisplayer.display("");

        if (region_name.equals("NorthEast")) {
            MessageDisplayer.display("Region is NorthEast. Test arrays equality");

            Assert.assertArrayEquals("Region is NorthEast. Test arrays equality", northEastRegion, zips);
        }
    }

    rs.close();

    MessageDisplayer.display("Done!");

}

From source file:org.opoo.oqs.core.AbstractQueryFactory.java

public void afterPropertiesSet() {
    String databaseName = null;/*  w  ww  .  j av a 2  s.  c  o  m*/
    int databaseMajorVersion = 0;
    Connection conn = null;
    try {
        conn = connectionManager.getConnection();
        DatabaseMetaData meta = conn.getMetaData();
        databaseName = meta.getDatabaseProductName();
        databaseMajorVersion = getDatabaseMajorVersion(meta);
        log.info("RDBMS: " + databaseName + ", version: " + meta.getDatabaseProductVersion());
        log.info("JDBC driver: " + meta.getDriverName() + ", version: " + meta.getDriverVersion());
    } catch (SQLException sqle) {
        log.warn("Could not obtain connection metadata", sqle);
    } catch (UnsupportedOperationException uoe) {
        // user supplied JDBC connections
    } finally {
        connectionManager.releaseConnection(conn);
    }
    if (dialect == null) {
        dialect = this.determineDialect(databaseName, databaseMajorVersion);
    }
}

From source file:org.kawanfw.test.api.client.RowIdTest.java

/**
 * @param connection/*ww w  .  j  a v  a 2s  . com*/
 *            the AceQL Connection
 * 
 * @throws SQLException
 * @throws Exception
 */
public void test(Connection connection) throws SQLException, Exception {

    MessageDisplayer.initClassDisplay(this.getClass().getSimpleName());

    DatabaseMetaData databaseMetaData = connection.getMetaData();
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductName()   : " + databaseMetaData.getDatabaseProductName());
    if (!new SqlUtil(connection).isOracle()) {
        MessageDisplayer.display("RowId tests are only supported in Oracle");
        return;
    }

    String sql = "select customer_id, rowid from customer where customer_id = ?";
    PreparedStatement prepStatement = connection.prepareStatement(sql);
    prepStatement.setInt(1, 1);
    ResultSet rs = prepStatement.executeQuery();

    RowId rowIdCustomer1 = null;

    while (rs.next()) {
        int customerId = rs.getInt("customer_id");
        rowIdCustomer1 = rs.getRowId(2);

        byte[] bytes = rowIdCustomer1.getBytes();
        String base64 = Base64.byteArrayToBase64(bytes);

        MessageDisplayer.display("customerId      : " + customerId);
        MessageDisplayer.display("rowId           : " + rowIdCustomer1.toString());
        MessageDisplayer.display("rowId.hashCode(): " + rowIdCustomer1.hashCode());
        MessageDisplayer.display("rowId.getBytes(): " + base64);
    }

    rs.close();

    boolean doUpdate = true;
    if (connection instanceof RemoteConnection) {
        RemoteConnection connectionHttp = (RemoteConnection) connection;
        if (connectionHttp.isStatelessMode()) {
            MessageDisplayer.display("setRowId is not supported in stateless mode");
            doUpdate = false;
        }
    }

    if (doUpdate) {
        sql = "update customer set lname = ?  where rowid = ?";
        PreparedStatement prepStatement2 = connection.prepareStatement(sql);
        prepStatement2.setString(1, "ROWID");
        prepStatement2.setRowId(2, rowIdCustomer1);
        int rc = prepStatement2.executeUpdate();
        MessageDisplayer.display("");
        MessageDisplayer.display("rc: " + rc);
        prepStatement2.close();
    }

    sql = "select customer_id, rowid from customer where customer_id = ?";
    prepStatement = connection.prepareStatement(sql);
    prepStatement.setInt(1, 1);
    ResultSet rs2 = prepStatement.executeQuery();

    RowId rowIdCustomer1New = null;

    while (rs2.next()) {
        int customerId = rs2.getInt("customer_id");
        rowIdCustomer1New = rs2.getRowId(2);

        byte[] bytes = rowIdCustomer1New.getBytes();
        String base64 = Base64.byteArrayToBase64(bytes);

        MessageDisplayer.display("customerId      : " + customerId);
        MessageDisplayer.display("rowId           : " + rowIdCustomer1New.toString());
        MessageDisplayer.display("rowId.hashCode(): " + rowIdCustomer1New.hashCode());
        MessageDisplayer.display("rowId.getBytes(): " + base64);
    }

    MessageDisplayer.display("");
    MessageDisplayer.display("Test RowIds are equal:");
    Assert.assertEquals("Set/read RowIds are equal", true, rowIdCustomer1.equals(rowIdCustomer1New));
    MessageDisplayer.display("Done!");

    prepStatement.close();
    rs2.close();

}

From source file:it.greenvulcano.gvesb.j2ee.db.connections.impl.DriverPoolConnectionBuilder.java

public Connection getConnection() throws GVDBException {
    try {/*from  w w w  . jav  a2s. com*/
        Connection conn = dataSource.getConnection();
        if (debugJDBCConn) {
            logger.debug("Created JDBC Connection [" + name + "]: [" + conn + "]");
            if (isFirst) {
                isFirst = false;
                DatabaseMetaData dbmd = conn.getMetaData();

                logger.debug("=====  Database info =====");
                logger.debug("DatabaseProductName: " + dbmd.getDatabaseProductName());
                logger.debug("DatabaseProductVersion: " + dbmd.getDatabaseProductVersion());
                logger.debug("DatabaseMajorVersion: " + dbmd.getDatabaseMajorVersion());
                logger.debug("DatabaseMinorVersion: " + dbmd.getDatabaseMinorVersion());
                logger.debug("=====  Driver info =====");
                logger.debug("DriverName: " + dbmd.getDriverName());
                logger.debug("DriverVersion: " + dbmd.getDriverVersion());
                logger.debug("DriverMajorVersion: " + dbmd.getDriverMajorVersion());
                logger.debug("DriverMinorVersion: " + dbmd.getDriverMinorVersion());
                logger.debug("=====  JDBC/DB attributes =====");
                if (dbmd.supportsGetGeneratedKeys())
                    logger.debug("Supports getGeneratedKeys(): true");
                else
                    logger.debug("Supports getGeneratedKeys(): false");
            }
        }

        return conn;
    } catch (Exception exc) {
        throw new GVDBException("DriverPoolConnectionBuilder - Error while creating Connection[" + name + "]",
                exc);
    }
}

From source file:org.openrdf.sail.rdbms.RdbmsStore.java

private RdbmsConnectionFactory newFactory(DatabaseMetaData metaData) throws SQLException {
    String dbn = metaData.getDatabaseProductName();
    String dbv = metaData.getDatabaseProductVersion();
    RdbmsConnectionFactory factory;/*from w  w w  . j  a va 2  s.  co m*/
    Iterator<RdbmsProvider> providers;
    providers = ServiceRegistry.lookupProviders(RdbmsProvider.class);
    while (providers.hasNext()) {
        RdbmsProvider provider = providers.next();
        factory = provider.createRdbmsConnectionFactory(dbn, dbv);
        if (factory != null)
            return factory;
    }
    return new RdbmsConnectionFactory();
}

From source file:org.artifactory.storage.db.DbServiceImpl.java

private void printConnectionInfo() throws SQLException {
    Connection connection = jdbcHelper.getDataSource().getConnection();
    try {//  ww  w .ja  va  2  s  .  c  o  m
        DatabaseMetaData meta = connection.getMetaData();
        log.info("Database: {} {}. Driver: {} {}", meta.getDatabaseProductName(),
                meta.getDatabaseProductVersion(), meta.getDriverName(), meta.getDriverVersion());
        log.info("Connection URL: {}", meta.getURL());
    } catch (SQLException e) {
        log.warn("Can not retrieve database and driver name / version", e);
    } finally {
        DbUtils.close(connection);
    }
}

From source file:com.googlecode.psiprobe.controllers.sql.ConnectionTestController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String resourceName = ServletRequestUtils.getStringParameter(request, "resource");
    DataSource dataSource = null;

    try {//from  w w  w. ja va 2s . c o  m
        dataSource = getContainerWrapper().getResourceResolver().lookupDataSource(context, resourceName,
                getContainerWrapper());
    } catch (NamingException e) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    }

    if (dataSource == null) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    } else {
        try {
            // TODO: use Spring's jdbc template?
            Connection conn = dataSource.getConnection();
            try {
                DatabaseMetaData md = conn.getMetaData();

                List dbMetaData = new ArrayList();

                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdName",
                        md.getDatabaseProductName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdVersion",
                        md.getDatabaseProductVersion());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverName",
                        md.getDriverName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverVersion",
                        md.getDriverVersion());
                //                    addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcVersion", String.valueOf(md.getJDBCMajorVersion()));

                return new ModelAndView(getViewName(), "dbMetaData", dbMetaData);
            } finally {
                conn.close();
            }
        } catch (SQLException e) {
            String message = getMessageSourceAccessor()
                    .getMessage("probe.src.dataSourceTest.connection.failure", new Object[] { e.getMessage() });
            logger.error(message, e);
            request.setAttribute("errorMessage", message);
        }
    }

    return new ModelAndView(getViewName());
}

From source file:com.netspective.axiom.connection.BasicConnectionProviderEntry.java

public void init(String dataSourceId, Connection conn) {
    this.dataSourceId = dataSourceId;

    try {//ww  w . j a  v  a2  s.  c  om
        try {
            DatabasePolicy policy = DatabasePolicies.getInstance().getDatabasePolicy(conn);
            put(KEYNAME_DATABASE_POLICY_CLASSNAME, policy.getClass().getName());
            put(KEYNAME_DATABASE_POLICY_DBMSID, policy.getDbmsIdentifier());
        } catch (Exception dpe) {
            put(KEYNAME_DATABASE_POLICY_CLASSNAME, dpe.toString());
        }

        DatabaseMetaData dbmd = conn.getMetaData();

        put(KEYNAME_DRIVER_NAME, dbmd.getDriverName());
        put(KEYNAME_DATABASE_PRODUCT_NAME, dbmd.getDatabaseProductName());
        put(KEYNAME_DATABASE_PRODUCT_VERSION, dbmd.getDatabaseProductVersion());
        put(KEYNAME_DRIVER_VERSION, dbmd.getDriverVersion());
        put(KEYNAME_URL, dbmd.getURL());
        put(KEYNAME_USER_NAME, dbmd.getUserName());

        String resultSetType = "unknown";
        if (dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE))
            resultSetType = "scrollable (insensitive)";
        else if (dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE))
            resultSetType = "scrollable (sensitive)";
        else if (dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY))
            resultSetType = "non-scrollabe (forward only)";
        put(KEYNAME_RESULTSET_TYPE, resultSetType);

        valid = true;
    } catch (Exception e) {
        exception = e;
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            log.error("SQL Exception while closing connection", e);
        }
    }
}

From source file:net.risesoft.soa.asf.web.controller.SystemController.java

private List<SysInfo> getDBInfo() {
    List list = new ArrayList();
    String group = "4. ??";
    try {//from   www .  j  a v  a  2s.c o m
        Connection conn = this.basicDataSource.getConnection();
        try {
            DatabaseMetaData dbmd = conn.getMetaData();
            list.add(new SysInfo("DatabaseProductName", dbmd.getDatabaseProductName(), group));
            list.add(new SysInfo("DatabaseProductVersion", dbmd.getDatabaseProductVersion(), group));
            list.add(new SysInfo("DatabaseMajorVersion", Integer.valueOf(dbmd.getDatabaseMajorVersion()),
                    group));
            list.add(new SysInfo("DatabaseMinorVersion", Integer.valueOf(dbmd.getDatabaseMinorVersion()),
                    group));
            list.add(new SysInfo("DriverName", dbmd.getDriverName(), group));
            list.add(new SysInfo("DriverVersion", dbmd.getDriverVersion(), group));
            list.add(new SysInfo("DriverMajorVersion", Integer.valueOf(dbmd.getDriverMajorVersion()), group));
            list.add(new SysInfo("DriverMinorVersion", Integer.valueOf(dbmd.getDriverMinorVersion()), group));
        } finally {
            conn.close();
        }
        group = "5. ?";
        BasicDataSource bds = this.basicDataSource;
        list.add(new SysInfo("InitialSize", Integer.valueOf(bds.getInitialSize()), group));
        list.add(new SysInfo("MaxActive", Integer.valueOf(bds.getMaxActive()), group));
        list.add(new SysInfo("MaxIdle", Integer.valueOf(bds.getMaxIdle()), group));
        list.add(new SysInfo("MinIdle", Integer.valueOf(bds.getMinIdle()), group));
        list.add(new SysInfo("MaxWait", Long.valueOf(bds.getMaxWait()), group));
        list.add(new SysInfo("NumActive", Integer.valueOf(bds.getNumActive()), group));
        list.add(new SysInfo("NumIdle", Integer.valueOf(bds.getNumIdle()), group));
        list.add(new SysInfo("DriverClass", bds.getDriverClassName(), group));
        list.add(new SysInfo("URL", bds.getUrl(), group));
        list.add(new SysInfo("Username", bds.getUsername(), group));
        list.add(new SysInfo("Password", "******", group));
    } catch (Exception ex) {
        log.warn("???: " + ex.getMessage(), ex);
    }
    return list;
}

From source file:org.wso2.carbon.policy.mgt.core.BasePolicyManagementDAOTest.java

protected Pair<Connection, Pair<DataSource, DataSource>> mockConnection() throws Exception {
    //Throwing PolicyManagerDAOException while adding profile
    DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class);
    when(databaseMetaData.getDatabaseProductName()).thenReturn("H2");

    Connection conn = mock(Connection.class);
    when(conn.getMetaData()).thenReturn(databaseMetaData);

    DataSource dataSource = mock(DataSource.class);
    when(dataSource.getConnection()).thenReturn(conn);

    Field dataSourceField = PolicyManagementDAOFactory.class.getDeclaredField("dataSource");
    dataSourceField.setAccessible(true);
    DataSource oldDataSource = (DataSource) dataSourceField.get(null);
    PolicyManagementDAOFactory.init(dataSource);

    return new Pair<>(conn, new Pair<>(oldDataSource, dataSource));
}