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:TestDatabaseMetaDataToolDatabaseInformation.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    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 {/*from  w w  w.  j a v  a  2  s  .c o  m*/
        int majorVersion = meta.getDatabaseMajorVersion();
        System.out.println("major Version: " + majorVersion);
    } catch (Exception e) {
        System.out.println("major Version: unsupported feature");
    }

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

    String productName = meta.getDatabaseProductName();
    String productVersion = meta.getDatabaseProductVersion();
    System.out.println("productName" + productName);
    System.out.println("productVersion" + productVersion);
    conn.close();
}

From source file:com.paladin.sys.db.DBManager.java

/**
 * init DataSource by spring/*from  w  ww  .ja  v  a 2  s.c o  m*/
 */
private static final void initDataSourceFromXml(String _xmpPath, String _beanName) {
    try {
        ApplicationContext factory = new ClassPathXmlApplicationContext(new String[] { _xmpPath });
        dataSource = (DataSource) factory.getBean(_beanName);
        Connection conn = getConnection();
        DatabaseMetaData mdm = conn.getMetaData();
        log.info("Connected to " + mdm.getDatabaseProductName() + " " + mdm.getDatabaseProductVersion());
        closeConnection();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.hyperic.hq.bizapp.server.session.SysStats.java

static Properties getDBStats(Connection connection) {
    Properties props = new Properties();
    DatabaseMetaData md;

    try {// w  w w  .j av a 2s. c o m
        md = connection.getMetaData();
        props.setProperty("hq.db.product.name", md.getDatabaseProductName());
        props.setProperty("hq.db.product.ver", md.getDatabaseProductVersion());
        props.setProperty("hq.db.driver.name", md.getDriverName());
        props.setProperty("hq.db.driver.ver", md.getDriverVersion());
    } catch (SQLException e) {
        _log.warn("Error get db stats");
        return props;
    }

    return props;
}

From source file:com.jagornet.dhcp.db.DbSchemaManager.java

/**
 * Validate schema./*www  .ja  v  a 2s .c  o  m*/
 * 
 * @param dataSource the data source
 * 
 * @throws SQLException if there is a problem with the database
 * @throws IOExcpetion if there is a problem reading the schema file
 * 
 * returns true if database was created, false otherwise
 */
public static boolean validateSchema(DataSource dataSource, String schemaFilename, int schemaVersion)
        throws SQLException, IOException {
    boolean schemaCreated = false;

    List<String> tableNames = new ArrayList<String>();

    Connection conn = dataSource.getConnection();
    DatabaseMetaData dbMetaData = conn.getMetaData();

    log.info("JDBC Connection Info:\n" + "url = " + dbMetaData.getURL() + "\n" + "database = "
            + dbMetaData.getDatabaseProductName() + " " + dbMetaData.getDatabaseProductVersion() + "\n"
            + "driver = " + dbMetaData.getDriverName() + " " + dbMetaData.getDriverVersion());

    String[] types = { "TABLE" };
    ResultSet rs = dbMetaData.getTables(null, null, "%", types);
    if (rs.next()) {
        tableNames.add(rs.getString("TABLE_NAME"));
    } else {
        createSchema(dataSource, schemaFilename);
        dbMetaData = conn.getMetaData();
        rs = dbMetaData.getTables(null, null, "%", types);
        schemaCreated = true;
    }
    while (rs.next()) {
        tableNames.add(rs.getString("TABLE_NAME"));
    }

    String[] schemaTableNames;
    if (schemaVersion <= 1) {
        schemaTableNames = TABLE_NAMES;
    } else {
        schemaTableNames = TABLE_NAMES_V2;
    }

    if (tableNames.size() == schemaTableNames.length) {
        for (int i = 0; i < schemaTableNames.length; i++) {
            if (!tableNames.contains(schemaTableNames[i])) {
                throw new IllegalStateException("Invalid database schema: unknown tables");
            }
        }
    } else {
        throw new IllegalStateException("Invalid database schema: wrong number of tables");
    }

    return schemaCreated;
}

From source file:com.aurel.track.admin.server.status.ServerStatusBL.java

private static void loadDatabaseInfo(ServerStatusTO serverStatusTO) {
    Connection conn = null;/* w w  w.  j  a v a 2 s. c o m*/
    try {
        conn = Torque.getConnection(BaseTSitePeer.DATABASE_NAME);
        DatabaseMetaData dbm = conn.getMetaData();
        serverStatusTO.setDatabase(dbm.getDatabaseProductName() + " " + dbm.getDatabaseProductVersion());
        serverStatusTO.setJdbcDriver(dbm.getDriverName() + " " + dbm.getDriverVersion());
        serverStatusTO.setJdbcUrl(dbm.getURL());
    } catch (Exception e) {
        LOGGER.error("Problem retrieving database meta data: " + e.getMessage());
    } finally {
        if (conn != null) {
            Torque.closeConnection(conn);
        }
    }
    Double ping = loadPing();
    serverStatusTO.setPingTime(ping.toString() + " ms");
}

From source file:org.springframework.batch.support.DatabaseTypeTestUtils.java

public static DataSource getMockDataSource(String databaseProductName, String databaseVersion)
        throws Exception {
    DatabaseMetaData dmd = mock(DatabaseMetaData.class);
    DataSource ds = mock(DataSource.class);
    Connection con = mock(Connection.class);
    when(ds.getConnection()).thenReturn(con);
    when(con.getMetaData()).thenReturn(dmd);
    when(dmd.getDatabaseProductName()).thenReturn(databaseProductName);
    if (databaseVersion != null) {
        when(dmd.getDatabaseProductVersion()).thenReturn(databaseVersion);
    }//from ww  w  .j ava  2  s  .  c o  m
    return ds;
}

From source file:TerminalMonitor.java

static public void showVersion(DatabaseMetaData meta) {
    try {/*from   w  w w  .  j  a v a  2 s .co  m*/
        System.out.println("TerminalMonitor v2.0");
        System.out.println("DBMS: " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion());
        System.out.println("JDBC Driver: " + meta.getDriverName() + " " + meta.getDriverVersion());
    } catch (SQLException e) {
        System.out.println("Failed to get version info: " + e.getMessage());
    }
}

From source file:org.jumpmind.db.platform.JdbcDatabasePlatformFactory.java

public static String getDatabaseProductVersion(DataSource dataSource) {
    Connection connection = null;

    try {//  ww w .j a v a2 s  . c  o  m
        connection = dataSource.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        return metaData.getDatabaseProductVersion();
    } catch (SQLException ex) {
        throw new SqlException("Error while reading the database metadata: " + ex.getMessage(), ex);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
                // we ignore this one
            }
        }
    }
}

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

/**
 * Create the dictionary using the given class name and properties; the
 * connection may be null if not supplied to the factory.
 *///from www.  j ava2s  . c  o  m
private static DBDictionary newDBDictionary(JDBCConfiguration conf, String dclass, String props,
        Connection conn) {
    DBDictionary dict = null;
    try {
        Class<?> c = Class.forName(dclass, true,
                AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(DBDictionary.class)));
        dict = (DBDictionary) AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(c));
    } catch (ClassNotFoundException cnfe) {
        // if the dictionary was not found, make another attempt
        // at loading the dictionary using the current thread.
        try {
            Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(dclass);
            dict = (DBDictionary) AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(c));
        } catch (Exception e) {
            if (e instanceof PrivilegedActionException)
                e = ((PrivilegedActionException) e).getException();
            throw new UserException(e).setFatal(true);
        }
    } catch (Exception e) {
        if (e instanceof PrivilegedActionException)
            e = ((PrivilegedActionException) e).getException();
        throw new UserException(e).setFatal(true);
    }

    // warn if we could not locate the appropriate dictionary
    Log log = conf.getLog(JDBCConfiguration.LOG_JDBC);
    if (log.isWarnEnabled() && dict.getClass() == DBDictionary.class)
        log.warn(_loc.get("warn-generic"));

    if (log.isInfoEnabled()) {
        String infoString = "";
        if (conn != null) {
            try {
                DatabaseMetaData meta = conn.getMetaData();
                infoString = " (" + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion()
                        + " ," + meta.getDriverName() + " " + meta.getDriverVersion() + ")";
            } catch (SQLException se) {
                if (log.isTraceEnabled())
                    log.trace(se.toString(), se);
            }
        }

        log.info(_loc.get("using-dict", dclass, infoString));
    }

    // set the dictionary's metadata
    Configurations.configureInstance(dict, conf, props, "DBDictionary");
    if (conn != null) {
        try {
            dict.connectedConfiguration(conn);
        } catch (SQLException se) {
            throw new StoreException(se).setFatal(true);
        }
    }
    return dict;
}

From source file:org.hyperic.util.jdbc.DBUtil.java

/**
 * Given a Connection object, this method returns a constant indicating what
 * type of database the Connection is connected to.
 * //w w w . j a  v  a  2s. co m
 * @param conn The connection whose database type the caller wished to
 *        ascertain.
 * @return One of the DATABASE_XXX constants defined in this class.
 */
public static int getDBType(Connection conn) throws SQLException {

    Class connClass = conn.getClass();
    Integer dbTypeInteger = (Integer) _dbTypes.get(connClass);
    int dbType = DATABASE_UNKNOWN;

    if (dbTypeInteger == null) {

        DatabaseMetaData dbMetaData = conn.getMetaData();
        String dbName = dbMetaData.getDatabaseProductName().toLowerCase();
        String dbVersion = dbMetaData.getDatabaseProductVersion().toLowerCase();
        log.debug("getDBType: dbName='" + dbName + "', version='" + dbVersion + "'");

        if (dbName.indexOf("postgresql") != -1) {
            if (dbVersion.startsWith("7.")) {
                dbType = DATABASE_POSTGRESQL_7;
            } else if (dbVersion.startsWith("8.")) {
                dbType = DATABASE_POSTGRESQL_8;
            } else if (dbVersion.startsWith("9.")) {
                dbType = DATABASE_POSTGRESQL_9;
            }
        } else if (dbName.indexOf("oracle") != -1) {
            if (dbVersion.startsWith("oracle8")) {
                dbType = DATABASE_ORACLE_8;
            } else if (dbVersion.startsWith("oracle9")) {
                dbType = DATABASE_ORACLE_9;
            } else if (dbVersion.startsWith("oracle database 10g")) {
                dbType = DATABASE_ORACLE_10;
            } else if (dbVersion.startsWith("oracle database 11g")) {
                dbType = DATABASE_ORACLE_11;
            }
        } else if (dbName.indexOf("mysql") != -1) {
            dbType = DATABASE_MYSQL5;
        }

        _dbTypes.put(connClass, new Integer(dbType));

    } else {
        dbType = dbTypeInteger.intValue();
    }

    return dbType;
}