Example usage for java.sql DatabaseMetaData getJDBCMajorVersion

List of usage examples for java.sql DatabaseMetaData getJDBCMajorVersion

Introduction

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

Prototype

int getJDBCMajorVersion() throws SQLException;

Source Link

Document

Retrieves the major JDBC version number for this driver.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();

    DatabaseMetaData md = conn.getMetaData();
    System.out.println(md.getJDBCMajorVersion());
    conn.close();/* w w  w  .  j  a va2s . c om*/
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    DatabaseMetaData meta = conn.getMetaData();
    // Oracle (and some other vendors) do not support
    // some the following methods; therefore, we need
    // to use try-catch block.
    try {/* w ww. j av  a 2 s .c  om*/
        int jdbcMajorVersion = meta.getJDBCMajorVersion();
        System.out.println("jdbcMajorVersion:" + jdbcMajorVersion);
    } catch (Exception e) {
        System.out.println("jdbcMajorVersion unsupported feature");
    }

    try {
        int jdbcMinorVersion = meta.getJDBCMinorVersion();
        System.out.println("jdbcMinorVersion:" + jdbcMinorVersion);
    } catch (Exception e) {
        System.out.println("jdbcMinorVersion unsupported feature");
    }

    String driverName = meta.getDriverName();
    String driverVersion = meta.getDriverVersion();
    System.out.println("driverName=" + driverName);
    System.out.println("driverVersion=" + driverVersion);

    st.close();
    conn.close();
}

From source file:net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.java

/**
 * /*from w  ww . j  a  v  a 2 s.co m*/
 */
public JRJdbcQueryExecuter(JasperReportsContext jasperReportsContext, JRDataset dataset,
        Map<String, ? extends JRValueParameter> parameters) {
    super(jasperReportsContext, dataset, parameters);

    connection = (Connection) getParameterValue(JRParameter.REPORT_CONNECTION);
    if (connection == null) {
        if (log.isWarnEnabled()) {
            log.warn("The supplied java.sql.Connection object is null.");
        }
    } else if (log.isDebugEnabled()) {
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            log.debug("DB is " + metaData.getDatabaseProductName() + " version "
                    + metaData.getDatabaseProductVersion() + " (" + metaData.getDatabaseMajorVersion() + "/"
                    + metaData.getDatabaseMinorVersion() + ")");
            log.debug("driver is " + metaData.getDriverName() + " version " + metaData.getDriverVersion() + " ("
                    + metaData.getDriverMajorVersion() + "/" + metaData.getDriverMinorVersion() + ")");
            log.debug("jdbc " + metaData.getJDBCMajorVersion() + "/" + metaData.getJDBCMinorVersion());
            log.debug("connection URL is " + metaData.getURL());
        } catch (SQLException e) {
            log.debug("failed to read connection metadata", e);
        }
    }

    isCachedRowSet = getBooleanParameterOrProperty(JRJdbcQueryExecuterFactory.PROPERTY_CACHED_ROWSET, false);

    setTimeZone();

    registerFunctions();

    parseQuery();
}

From source file:com.manydesigns.portofino.model.database.ConnectionProvider.java

public void init(DatabasePlatformsRegistry databasePlatformsRegistry) {
    Connection conn = null;//from   www . jav a 2  s.c om
    ResultSet typeRs = null;
    String databaseName = getDatabase().getDatabaseName();
    try {
        conn = acquireConnection();

        DatabaseMetaData metadata = conn.getMetaData();

        databaseProductName = metadata.getDatabaseProductName();
        databaseProductVersion = metadata.getDatabaseProductVersion();

        try {
            databaseMajorVersion = metadata.getDatabaseMajorVersion();
            databaseMinorVersion = metadata.getDatabaseMinorVersion();
            databaseMajorMinorVersion = MessageFormat.format("{0}.{1}", databaseMajorVersion,
                    databaseMinorVersion);
        } catch (SQLException e) {
            databaseMajorMinorVersion = e.getMessage();
        }

        driverName = metadata.getDriverName();
        driverVersion = metadata.getDriverVersion();

        driverMajorVersion = metadata.getDriverMajorVersion();
        driverMinorVersion = metadata.getDriverMinorVersion();
        driverMajorMinorVersion = MessageFormat.format("{0}.{1}", driverMajorVersion, driverMinorVersion);

        try {
            JDBCMajorVersion = metadata.getJDBCMajorVersion();
            JDBCMinorVersion = metadata.getJDBCMinorVersion();
            JDBCMajorMinorVersion = MessageFormat.format("{0}.{1}", JDBCMajorVersion, JDBCMinorVersion);
        } catch (Throwable e) {
            JDBCMajorMinorVersion = e.getMessage();
        }

        // extract supported types
        types.clear();
        typeRs = metadata.getTypeInfo();
        while (typeRs.next()) {
            readType(typeRs);
        }
        fixMissingTypeAliases(types);
        Collections.sort(types, new TypeComparator());

        databasePlatform = databasePlatformsRegistry.findApplicableAbstraction(this);
        if (databasePlatform == null) {
            status = STATUS_ERROR;
            errorMessage = MessageFormat.format("Database platform not found for {0}", databaseProductName);
            logger.warn(errorMessage);
        } else {
            status = STATUS_CONNECTED;
            errorMessage = null;
        }
    } catch (Throwable e) {
        status = STATUS_ERROR;
        errorMessage = e.getMessage();
        logger.warn("Could not create database platform for " + databaseName, e);
    } finally {
        DbUtil.closeResultSetAndStatement(typeRs);
        releaseConnection(conn);
        lastTested = new Date();
    }
}

From source file:org.apache.bigtop.itest.hive.TestJdbc.java

/**
 * Test simple DatabaseMetaData calls.  getColumns is tested elsewhere, as we need to call
 * that on a valid table.  Same with getFunctions.
 *
 * @throws SQLException// ww w .  j a  v  a2  s .c o  m
 */
@Test
public void databaseMetaDataCalls() throws SQLException {
    DatabaseMetaData md = conn.getMetaData();

    boolean boolrc = md.allTablesAreSelectable();
    LOG.debug("All tables are selectable? " + boolrc);

    String strrc = md.getCatalogSeparator();
    LOG.debug("Catalog separator " + strrc);

    strrc = md.getCatalogTerm();
    LOG.debug("Catalog term " + strrc);

    ResultSet rs = md.getCatalogs();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found catalog " + strrc);
    }

    Connection c = md.getConnection();

    int intrc = md.getDatabaseMajorVersion();
    LOG.debug("DB major version is " + intrc);

    intrc = md.getDatabaseMinorVersion();
    LOG.debug("DB minor version is " + intrc);

    strrc = md.getDatabaseProductName();
    LOG.debug("DB product name is " + strrc);

    strrc = md.getDatabaseProductVersion();
    LOG.debug("DB product version is " + strrc);

    intrc = md.getDefaultTransactionIsolation();
    LOG.debug("Default transaction isolation is " + intrc);

    intrc = md.getDriverMajorVersion();
    LOG.debug("Driver major version is " + intrc);

    intrc = md.getDriverMinorVersion();
    LOG.debug("Driver minor version is " + intrc);

    strrc = md.getDriverName();
    LOG.debug("Driver name is " + strrc);

    strrc = md.getDriverVersion();
    LOG.debug("Driver version is " + strrc);

    strrc = md.getExtraNameCharacters();
    LOG.debug("Extra name characters is " + strrc);

    strrc = md.getIdentifierQuoteString();
    LOG.debug("Identifier quote string is " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getImportedKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getIndexInfo("a", "b", "d", true, true);

    intrc = md.getJDBCMajorVersion();
    LOG.debug("JDBC major version is " + intrc);

    intrc = md.getJDBCMinorVersion();
    LOG.debug("JDBC minor version is " + intrc);

    intrc = md.getMaxColumnNameLength();
    LOG.debug("Maximum column name length is " + intrc);

    strrc = md.getNumericFunctions();
    LOG.debug("Numeric functions are " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getPrimaryKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedureColumns("a", "b", "d", "e");

    strrc = md.getProcedureTerm();
    LOG.debug("Procedures are called " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedures("a", "b", "d");

    strrc = md.getSchemaTerm();
    LOG.debug("Schemas are called " + strrc);

    rs = md.getSchemas();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found schema " + strrc);
    }

    strrc = md.getSearchStringEscape();
    LOG.debug("Search string escape is " + strrc);

    strrc = md.getStringFunctions();
    LOG.debug("String functions are " + strrc);

    strrc = md.getSystemFunctions();
    LOG.debug("System functions are " + strrc);

    rs = md.getTableTypes();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found table type " + strrc);
    }

    strrc = md.getTimeDateFunctions();
    LOG.debug("Time/date functions are " + strrc);

    rs = md.getTypeInfo();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found type " + strrc);
    }

    // In Hive 1.2 this always returns an empty RS
    rs = md.getUDTs("a", "b", "d", null);

    boolrc = md.supportsAlterTableWithAddColumn();
    LOG.debug("Supports alter table with add column? " + boolrc);

    boolrc = md.supportsAlterTableWithDropColumn();
    LOG.debug("Supports alter table with drop column? " + boolrc);

    boolrc = md.supportsBatchUpdates();
    LOG.debug("Supports batch updates? " + boolrc);

    boolrc = md.supportsCatalogsInDataManipulation();
    LOG.debug("Supports catalogs in data manipulation? " + boolrc);

    boolrc = md.supportsCatalogsInIndexDefinitions();
    LOG.debug("Supports catalogs in index definition? " + boolrc);

    boolrc = md.supportsCatalogsInPrivilegeDefinitions();
    LOG.debug("Supports catalogs in privilege definition? " + boolrc);

    boolrc = md.supportsCatalogsInProcedureCalls();
    LOG.debug("Supports catalogs in procedure calls? " + boolrc);

    boolrc = md.supportsCatalogsInTableDefinitions();
    LOG.debug("Supports catalogs in table definition? " + boolrc);

    boolrc = md.supportsColumnAliasing();
    LOG.debug("Supports column aliasing? " + boolrc);

    boolrc = md.supportsFullOuterJoins();
    LOG.debug("Supports full outer joins? " + boolrc);

    boolrc = md.supportsGroupBy();
    LOG.debug("Supports group by? " + boolrc);

    boolrc = md.supportsLimitedOuterJoins();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsMultipleResultSets();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsNonNullableColumns();
    LOG.debug("Supports non-nullable columns? " + boolrc);

    boolrc = md.supportsOuterJoins();
    LOG.debug("Supports outer joins? " + boolrc);

    boolrc = md.supportsPositionedDelete();
    LOG.debug("Supports positioned delete? " + boolrc);

    boolrc = md.supportsPositionedUpdate();
    LOG.debug("Supports positioned update? " + boolrc);

    boolrc = md.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set holdability? " + boolrc);

    boolrc = md.supportsResultSetType(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set type? " + boolrc);

    boolrc = md.supportsSavepoints();
    LOG.debug("Supports savepoints? " + boolrc);

    boolrc = md.supportsSchemasInDataManipulation();
    LOG.debug("Supports schemas in data manipulation? " + boolrc);

    boolrc = md.supportsSchemasInIndexDefinitions();
    LOG.debug("Supports schemas in index definitions? " + boolrc);

    boolrc = md.supportsSchemasInPrivilegeDefinitions();
    LOG.debug("Supports schemas in privilege definitions? " + boolrc);

    boolrc = md.supportsSchemasInProcedureCalls();
    LOG.debug("Supports schemas in procedure calls? " + boolrc);

    boolrc = md.supportsSchemasInTableDefinitions();
    LOG.debug("Supports schemas in table definitions? " + boolrc);

    boolrc = md.supportsSelectForUpdate();
    LOG.debug("Supports select for update? " + boolrc);

    boolrc = md.supportsStoredProcedures();
    LOG.debug("Supports stored procedures? " + boolrc);

    boolrc = md.supportsTransactions();
    LOG.debug("Supports transactions? " + boolrc);

    boolrc = md.supportsUnion();
    LOG.debug("Supports union? " + boolrc);

    boolrc = md.supportsUnionAll();
    LOG.debug("Supports union all? " + boolrc);

}

From source file:org.apache.ddlutils.TestSummaryCreatorTask.java

/**
 * Adds the data from the test jdbc propertis file to the document.
 * //from w w  w. j a  v a2  s .c  o m
 * @param element            The element to add the relevant database properties to
 * @param jdbcPropertiesFile The path of the properties file
 */
protected void addTargetDatabaseInfo(Element element, String jdbcPropertiesFile)
        throws IOException, BuildException {
    if (jdbcPropertiesFile == null) {
        return;
    }

    Properties props = readProperties(jdbcPropertiesFile);
    Connection conn = null;
    DatabaseMetaData metaData = null;

    try {
        String dataSourceClass = props.getProperty(
                TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX + "class",
                BasicDataSource.class.getName());
        DataSource dataSource = (DataSource) Class.forName(dataSourceClass).newInstance();

        for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            String propName = (String) entry.getKey();

            if (propName.startsWith(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX)
                    && !propName.equals(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX + "class")) {
                BeanUtils.setProperty(dataSource,
                        propName.substring(TestAgainstLiveDatabaseBase.DATASOURCE_PROPERTY_PREFIX.length()),
                        entry.getValue());
            }
        }

        String platformName = props.getProperty(TestAgainstLiveDatabaseBase.DDLUTILS_PLATFORM_PROPERTY);

        if (platformName == null) {
            platformName = new PlatformUtils().determineDatabaseType(dataSource);
            if (platformName == null) {
                throw new BuildException(
                        "Could not determine platform from datasource, please specify it in the jdbc.properties via the ddlutils.platform property");
            }
        }

        element.addAttribute("platform", platformName);
        element.addAttribute("dataSourceClass", dataSourceClass);

        conn = dataSource.getConnection();
        metaData = conn.getMetaData();

        try {
            element.addAttribute("dbProductName", metaData.getDatabaseProductName());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            element.addAttribute("dbProductVersion", metaData.getDatabaseProductVersion());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            int databaseMajorVersion = metaData.getDatabaseMajorVersion();
            int databaseMinorVersion = metaData.getDatabaseMinorVersion();

            element.addAttribute("dbVersion", databaseMajorVersion + "." + databaseMinorVersion);
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            element.addAttribute("driverName", metaData.getDriverName());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            element.addAttribute("driverVersion", metaData.getDriverVersion());
        } catch (Throwable ex) {
            // we ignore it
        }
        try {
            int jdbcMajorVersion = metaData.getJDBCMajorVersion();
            int jdbcMinorVersion = metaData.getJDBCMinorVersion();

            element.addAttribute("jdbcVersion", jdbcMajorVersion + "." + jdbcMinorVersion);
        } catch (Throwable ex) {
            // we ignore it
        }
    } catch (Exception ex) {
        throw new BuildException(ex);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                // we ignore it
            }
        }
    }
}

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

/**
 * This method is called when the dictionary first sees any connection.
 * It is used to initialize dictionary metadata if needed. If you
 * override this method, be sure to call
 * <code>super.connectedConfiguration</code>.
 *//*from   w ww . j  a v  a 2s.  c o m*/
public void connectedConfiguration(Connection conn) throws SQLException {
    if (!connected) {
        DatabaseMetaData metaData = null;
        try {
            metaData = conn.getMetaData();

            databaseProductName = nullSafe(metaData.getDatabaseProductName());
            databaseProductVersion = nullSafe(metaData.getDatabaseProductVersion());
            setMajorVersion(metaData.getDatabaseMajorVersion());
            setMinorVersion(metaData.getDatabaseMinorVersion());
            try {
                // JDBC3-only method, so it might throw an
                // AbstractMethodError
                int JDBCMajorVersion = metaData.getJDBCMajorVersion();
                isJDBC3 = JDBCMajorVersion >= 3;
                isJDBC4 = JDBCMajorVersion >= 4;
            } catch (Throwable t) {
                // ignore if not JDBC3
            }
        } catch (Exception e) {
            if (log.isTraceEnabled())
                log.trace(e.toString(), e);
        }

        if (log.isTraceEnabled()) {
            log.trace(DBDictionaryFactory.toString(metaData));

            if (isJDBC3) {
                try {
                    log.trace(_loc.get("connection-defaults", new Object[] { conn.getAutoCommit(),
                            conn.getHoldability(), conn.getTransactionIsolation() }));
                } catch (Throwable t) {
                    log.trace("Unable to trace connection settings", t);
                }
            }
        }

        // Configure the naming utility
        if (supportsDelimitedIdentifiers == null) // not explicitly set
            configureNamingUtil(metaData);

        // Auto-detect generated keys retrieval support unless user specified it.
        if (supportsGetGeneratedKeys == null) {
            supportsGetGeneratedKeys = (isJDBC3) ? metaData.supportsGetGeneratedKeys() : false;
        }
        if (log.isInfoEnabled()) {
            log.info(_loc.get("dict-info", new Object[] { metaData.getDatabaseProductName(), getMajorVersion(),
                    getMinorVersion(), metaData.getDriverName(), metaData.getDriverVersion() }));
        }
    }
    connected = true;
}

From source file:org.beangle.webapp.database.action.DatasourceAction.java

public String test() {
    Long datasourceId = getEntityId("datasource");
    DataSource dataSource = datasourceService.getDatasource(datasourceId);
    Map<String, String> driverinfo = CollectUtils.newHashMap();
    Map<String, Object> dbinfo = CollectUtils.newHashMap();
    Map<String, Object> jdbcinfo = CollectUtils.newHashMap();
    Connection con = null;// w w w .j  a  v a  2 s  .  c o m
    try {
        con = dataSource.getConnection();
        if (con != null) {
            java.sql.DatabaseMetaData dm = con.getMetaData();
            driverinfo.put("Driver Name", dm.getDriverName());
            driverinfo.put("Driver Version", dm.getDriverVersion());
            dbinfo.put("Database Name", dm.getDatabaseProductName());
            dbinfo.put("Database Version", dm.getDatabaseProductVersion());
            jdbcinfo.put("JDBC Version", dm.getJDBCMajorVersion() + "." + dm.getJDBCMinorVersion());
            StringBuilder catelogs = new StringBuilder();
            dbinfo.put("Avalilable Catalogs", catelogs);
            java.sql.ResultSet rs = dm.getCatalogs();
            while (rs.next()) {
                catelogs.append(rs.getString(1));
                if (rs.next())
                    catelogs.append(',');
            }
            rs.close();
        }
    } catch (Exception e) {
        put("exceptionStack", ExceptionUtils.getFullStackTrace(e));
    } finally {
        try {
            if (con != null)
                con.close();
            con = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    put("driverinfo", driverinfo);
    put("dbinfo", dbinfo);
    put("jdbcinfo", jdbcinfo);
    return forward();
}

From source file:org.seasar.dbflute.helper.jdbc.connection.DfDataSourceHandler.java

protected void processConnectionMetaInfo(Connection conn) throws SQLException {
    if (_alreadySetupMeta) {
        return;/* w  w w  .j  a v a2  s.  co  m*/
    }
    try {
        final DfConnectionMetaInfo metaInfo = new DfConnectionMetaInfo();
        final DatabaseMetaData metaData = conn.getMetaData();
        metaInfo.setProductName(metaData.getDatabaseProductName());
        metaInfo.setProductVersion(metaData.getDatabaseProductVersion());
        metaInfo.setDriverName(metaData.getDriverName());
        metaInfo.setDriverVersion(metaData.getDriverVersion());
        final int majorVersion = metaData.getJDBCMajorVersion();
        final int minorVersion = metaData.getJDBCMinorVersion();
        metaInfo.setJdbcVersion(majorVersion + "." + minorVersion);
        _log.info("  product = " + metaInfo.getProductDisp());
        _log.info("  driver  = " + metaInfo.getDriverDisp());
        _connectionMetaInfo = metaInfo;
    } catch (SQLException continued) {
        _log.info("*Failed to get connection meta: " + continued.getMessage());
        _connectionMetaInfo = null;
    }
    _alreadySetupMeta = true;
}