Example usage for java.sql DatabaseMetaData getDatabaseProductVersion

List of usage examples for java.sql DatabaseMetaData getDatabaseProductVersion

Introduction

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

Prototype

String getDatabaseProductVersion() throws SQLException;

Source Link

Document

Retrieves the version number of this database product.

Usage

From source file:org.apache.geronimo.console.databasemanager.wizard.DatabasePoolPortlet.java

private static String attemptConnect(PortletRequest request, PoolData data)
        throws SQLException, IllegalAccessException, InstantiationException {
    Class driverClass = attemptDriverLoad(request, data);
    Driver driver = (Driver) driverClass.newInstance();
    if (driver.acceptsURL(data.url)) {
        Properties props = new Properties();
        if (data.user != null) {
            props.put("user", data.user);
        }//from ww  w. ja  v  a2  s.co m
        if (data.password != null) {
            props.put("password", data.password);
        }
        Connection con = null;
        try {
            con = driver.connect(data.url, props);
            final DatabaseMetaData metaData = con.getMetaData();
            return metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion();
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    //ignore
                }
            }
        }
    } else
        throw new SQLException("Driver " + data.getDriverClass() + " does not accept URL " + data.url);
}

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 {/*from   w w  w .j  av a  2  s .  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:mondrian.spi.impl.JdbcDialectImpl.java

protected String deduceProductVersion(DatabaseMetaData databaseMetaData) {
    String productVersion;/*from  w w w.j av  a 2  s  .  c  o  m*/
    try {
        productVersion = databaseMetaData.getDatabaseProductVersion();
    } catch (SQLException e11) {
        throw Util.newInternal(e11, "while detecting database product version");
    }
    return productVersion;
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

public void logDatabaseAndDriverInfo(ConnectionManager connectionManager) throws SQLException {
    DatabaseMetaData databaseMetaData = connectionManager.getConnection().getMetaData();
    LOG.info("Database Product name: {}", databaseMetaData.getDatabaseProductName());
    LOG.info("Database product version: {}", databaseMetaData.getDatabaseProductVersion());
    LOG.info("Driver name: {}", databaseMetaData.getDriverName());
    LOG.info("Driver version: {}", databaseMetaData.getDriverVersion());
}

From source file:com.aurel.track.ApplicationStarter.java

private void printSystemInfo() {
    LOGGER.info("Java: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version"));
    LOGGER.info("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.arch"));
    Locale loc = Locale.getDefault();
    LOGGER.info("Default locale: " + loc.getDisplayName());

    ServletContext application = ApplicationBean.getInstance().getServletContext();
    try {//from  w ww .  j  av  a  2s .  c  o  m
        LOGGER.info("Servlet real path: " + application.getRealPath(File.separator));
    } catch (Exception ex) {
        LOGGER.error("Error trying to obtain getRealPath()");
    }
    LOGGER.info("Servlet container: " + application.getServerInfo());

    Connection conn = null;
    try {
        PropertiesConfiguration pc = ApplicationBean.getInstance().getDbConfig();
        LOGGER.info("Configured database type: " + pc.getProperty("torque.database.track.adapter"));
        LOGGER.info(
                "Configured database driver: " + pc.getProperty("torque.dsfactory.track.connection.driver"));
        LOGGER.info("Configured JDBC URL: " + pc.getProperty("torque.dsfactory.track.connection.url"));
        conn = Torque.getConnection(BaseTSitePeer.DATABASE_NAME);
        DatabaseMetaData dbm = conn.getMetaData();
        LOGGER.info("Database type: " + dbm.getDatabaseProductName() + " " + dbm.getDatabaseProductVersion());
        LOGGER.info("Driver info:   " + dbm.getDriverName() + " " + dbm.getDriverVersion());
        Statement stmt = conn.createStatement();
        Date d1 = new Date();
        stmt.executeQuery("SELECT * FROM TSTATE");
        Date d2 = new Date();
        stmt.close();
        LOGGER.info("Database test query done in " + (d2.getTime() - d1.getTime()) + " milliseconds ");
    } catch (Exception e) {
        System.err.println("Problem retrieving meta data");
        LOGGER.error("Problem retrieving meta data");
    } finally {
        if (conn != null) {
            Torque.closeConnection(conn);
        }
    }
}

From source file:org.openadaptor.auxil.connector.jdbc.writer.AbstractSQLWriter.java

protected void logDBInfo(DatabaseMetaData dmd) throws SQLException {
    if (debug_db_version_not_logged && log.isDebugEnabled()) {
        String productName = dmd.getDatabaseProductName();
        try {/*  w  w w  . j a v  a 2 s . co m*/
            log.debug("DB Name (version major/minor): " + productName + " (" + dmd.getDatabaseMajorVersion()
                    + "/" + dmd.getDatabaseMinorVersion() + ")");
        } catch (AbstractMethodError ame) { //Sybase jconn2 driver doesn't implement the maj/min methods.
            log.debug("DB Name: " + productName);
        }
        log.debug("DB Version: " + dmd.getDatabaseProductVersion());
        debug_db_version_not_logged = false; //Don't report it any more.
    }
}

From source file:ro.nextreports.designer.dbviewer.DefaultDBViewer.java

public DBInfo getDBInfo(String schemaName, int mask, Connection con) throws NextSqlException {

    String info = "";
    List<String> keywords = new ArrayList<String>();
    List<DBTable> tables = new ArrayList<DBTable>();
    List<DBProcedure> procedures = new ArrayList<DBProcedure>();
    Dialect dialect;//  w w w  .  j  av a  2  s  .  c o m

    try {
        dialect = DialectUtil.getDialect(con);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new NextSqlException("Could not get Dialect.", ex);
    }

    try {
        DatabaseMetaData dbmd = con.getMetaData();

        if ((mask & DBInfo.INFO) == DBInfo.INFO) {
            StringBuffer sb = new StringBuffer();
            sb.append(I18NSupport.getString("database.product")).append(dbmd.getDatabaseProductName())
                    .append("\r\n");
            sb.append(I18NSupport.getString("database.product.version"))
                    .append(dbmd.getDatabaseProductVersion()).append("\r\n");
            sb.append(I18NSupport.getString("database.driver.name")).append(dbmd.getDriverName())
                    .append("\r\n");
            sb.append(I18NSupport.getString("database.driver.version")).append(dbmd.getDriverVersion())
                    .append("\r\n");
            info = sb.toString();
        }

        if ((mask & DBInfo.SUPPORTED_KEYWORDS) == DBInfo.SUPPORTED_KEYWORDS) {
            StringTokenizer st = new StringTokenizer(dbmd.getSQLKeywords(), ",");
            while (st.hasMoreTokens()) {
                keywords.add(st.nextToken());
            }
        }

        // Get a ResultSet that contains all of the tables in this database
        // We specify a table_type of "TABLE" to prevent seeing system tables,
        // views and so forth
        boolean tableMask = ((mask & DBInfo.TABLES) == DBInfo.TABLES);
        boolean viewMask = ((mask & DBInfo.VIEWS) == DBInfo.VIEWS);
        if (tableMask || viewMask) {
            String[] tableTypes;
            if (tableMask && viewMask) {
                tableTypes = new String[] { "TABLE", "VIEW" };
            } else if (tableMask) {
                tableTypes = new String[] { "TABLE" };
            } else {
                tableTypes = new String[] { "VIEW" };
            }

            String pattern = tableMask ? Globals.getTableNamePattern() : Globals.getViewNamePattern();
            ResultSet allTables = dbmd.getTables(null, schemaName, pattern, tableTypes);
            try {
                while (allTables.next()) {
                    String table_name = allTables.getString("TABLE_NAME");
                    String table_type = allTables.getString("TABLE_TYPE");

                    // discard recycle bin tables
                    String ignoreTablePrefix = dialect.getRecycleBinTablePrefix();
                    if ((table_name == null)
                            || ((ignoreTablePrefix != null) && table_name.startsWith(ignoreTablePrefix))) {
                        continue;
                    }

                    if ((mask & DBInfo.INDEXES) == DBInfo.INDEXES) {
                        ResultSet indexList = null;
                        try {
                            // Get a list of all the indexes for this table
                            indexList = dbmd.getIndexInfo(null, schemaName, table_name, false, false);
                            List<DBIndex> indexes = new ArrayList<DBIndex>();
                            while (indexList.next()) {
                                String index_name = indexList.getString("INDEX_NAME");
                                String column_name = indexList.getString("COLUMN_NAME");
                                if (!index_name.equals("null")) {
                                    DBIndex index = new DBIndex(index_name, column_name);
                                    indexes.add(index);
                                }
                            }
                            DBTable table = new DBTable(schemaName, table_name, table_type, indexes);
                            tables.add(table);

                        } catch (SQLException e) {
                            throw new NextSqlException("SQL Exception: " + e.getMessage(), e);
                        } finally {
                            closeResultSet(indexList);
                        }

                    } else {
                        DBTable table = new DBTable(schemaName, table_name, table_type);
                        tables.add(table);
                    }
                }
            } catch (SQLException e) {
                throw new NextSqlException("SQL Exception: " + e.getMessage(), e);
            } finally {
                closeResultSet(allTables);
            }

        }

        boolean procedureMask = ((mask & DBInfo.PROCEDURES) == DBInfo.PROCEDURES);
        if (procedureMask) {
            String pattern = Globals.getProcedureNamePattern();
            if (pattern == null) {
                pattern = "%";
            }
            ResultSet rs = dbmd.getProcedures(null, schemaName, pattern);
            try {
                while (rs.next()) {
                    String spName = rs.getString("PROCEDURE_NAME");
                    int spType = rs.getInt("PROCEDURE_TYPE");
                    String catalog = rs.getString("PROCEDURE_CAT");
                    //                        System.out.println("Stored Procedure Name: " + spName);
                    //                        if (spType == DatabaseMetaData.procedureReturnsResult) {
                    //                            System.out.println("procedure Returns Result");
                    //                        } else if (spType == DatabaseMetaData.procedureNoResult) {
                    //                            System.out.println("procedure No Result");
                    //                        } else {
                    //                            System.out.println("procedure Result unknown");
                    //                        }
                    procedures.add(new DBProcedure(schemaName, catalog, spName, spType));
                }
            } catch (SQLException e) {
                throw new NextSqlException("SQL Exception: " + e.getMessage(), e);
            } finally {
                closeResultSet(rs);
            }
        }

    } catch (SQLException e) {
        LOG.error(e.getMessage(), e);
        e.printStackTrace();
        throw new NextSqlException("SQL Exception: " + e.getMessage(), e);
    }

    return new DBInfo(info, tables, procedures, keywords);
}

From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java

public void testDatabaseMetaData() throws SQLException {
    DatabaseMetaData meta = con.getMetaData();

    assertEquals("Hive", meta.getDatabaseProductName());
    assertEquals("1", meta.getDatabaseProductVersion());
    assertEquals(DatabaseMetaData.sqlStateSQL99, meta.getSQLStateType());
    assertNull(meta.getProcedures(null, null, null));
    assertFalse(meta.supportsCatalogsInTableDefinitions());
    assertFalse(meta.supportsSchemasInTableDefinitions());
    assertFalse(meta.supportsSchemasInDataManipulation());
    assertFalse(meta.supportsMultipleResultSets());
    assertFalse(meta.supportsStoredProcedures());
    assertTrue(meta.supportsAlterTableWithAddColumn());
}

From source file:org.apache.torque.task.TorqueSQLExec.java

/**
 * Verify if connected to the correct RDBMS
 *
 * @param conn//from  ww  w  .  j  a  va 2 s  . c o m
 */
protected boolean isValidRdbms(Connection conn) {
    if (rdbms == null && version == null) {
        return true;
    }

    try {
        DatabaseMetaData dmd = conn.getMetaData();

        if (rdbms != null) {
            String theVendor = dmd.getDatabaseProductName().toLowerCase();

            log("RDBMS = " + theVendor, Project.MSG_VERBOSE);
            if (theVendor == null || theVendor.indexOf(rdbms) < 0) {
                log("Not the required RDBMS: " + rdbms, Project.MSG_VERBOSE);
                return false;
            }
        }

        if (version != null) {
            String theVersion = dmd.getDatabaseProductVersion().toLowerCase();

            log("Version = " + theVersion, Project.MSG_VERBOSE);
            if (theVersion == null
                    || !(theVersion.startsWith(version) || theVersion.indexOf(" " + version) >= 0)) {
                log("Not the required version: \"" + version + "\"", Project.MSG_VERBOSE);
                return false;
            }
        }
    } catch (SQLException e) {
        // Could not get the required information
        log("Failed to obtain required RDBMS information", Project.MSG_ERR);
        return false;
    }

    return true;
}

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

/**
 * Determine XML column support and backslash handling.
 *///from ww w.  j a v a2  s  . c  om
public void connectedConfiguration(Connection conn) throws SQLException {
    super.connectedConfiguration(conn);

    DatabaseMetaData metaData = conn.getMetaData();
    int maj = 0;
    int min = 0;
    if (isJDBC3) {
        maj = metaData.getDatabaseMajorVersion();
        min = metaData.getDatabaseMinorVersion();
    } else {
        try {
            // The product version looks like "8.3.5".
            String productVersion = metaData.getDatabaseProductVersion();
            String majMin[] = productVersion.split("\\.");
            maj = Integer.parseInt(majMin[0]);
            min = Integer.parseInt(majMin[1]);
        } catch (Exception e) {
            // We don't understand the version format.
            if (log.isWarnEnabled())
                log.warn(e.toString(), e);
        }
    }

    if ((maj >= 9 || (maj == 8 && min >= 3))) {
        supportsXMLColumn = true;
    }
    // Old PostgreSQL requires double-escape for strings.
    if ((maj <= 8 || (maj == 9 && min == 0))) {
        requiresSearchStringEscapeForLike = true;
        searchStringEscape = "\\\\";
    }
}