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.wso2.carbon.dashboard.portal.core.datasource.DataBaseInitializer.java

/**
 * To get the database type used by the user
 *
 * @param conn Connection of the datasource
 * @return type of the database//  ww  w.j av a2  s . co m
 * @throws DashboardPortalException
 */
private String getDatabaseType(Connection conn) throws DashboardPortalException {
    String type = null;
    try {
        if (conn != null && (!conn.isClosed())) {
            DatabaseMetaData metaData = conn.getMetaData();
            String databaseProductName = metaData.getDatabaseProductName();
            if (databaseProductName.matches("(?i).*mysql.*")) {
                type = "mysql";
            } else if (databaseProductName.matches("(?i).*oracle.*")) {
                type = "oracle";
            } else if (databaseProductName.matches("(?i).*microsoft.*")) {
                type = "mssql";
            } else if (databaseProductName.matches("(?i).*h2.*")) {
                type = "h2";
            } else {
                String msg = "Unsupported database: " + databaseProductName
                        + ". Database will not be created automatically by the WSO2 Dashboard Server. "
                        + "Please create the database using appropriate database scripts for "
                        + "the database.";
                throw new DashboardPortalException(msg, null);
            }
        }
    } catch (SQLException e) {
        throw new DashboardPortalException("Failed to create tables for dashboards database.", e);
    }
    return type;
}

From source file:org.apache.hadoop.mapreduce.lib.db.DBInputFormat.java

/** {@inheritDoc} */
public void setConf(Configuration conf) {

    dbConf = new DBConfiguration(conf);

    try {//from   w  w w .ja  va 2  s .  c  o m
        this.connection = createConnection();

        DatabaseMetaData dbMeta = connection.getMetaData();
        this.dbProductName = StringUtils.toUpperCase(dbMeta.getDatabaseProductName());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    tableName = dbConf.getInputTableName();
    fieldNames = dbConf.getInputFieldNames();
    conditions = dbConf.getInputConditions();
}

From source file:org.apache.sqoop.mapreduce.db.DBInputFormat.java

public Connection getConnection() {
    try {/*from  w  w  w  .  ja  v  a2  s .c o m*/

        if (null == this.connection) {
            // The connection was closed; reinstantiate it.
            this.connection = dbConf.getConnection();
            this.connection.setAutoCommit(false);
            DatabaseMetaData dbMeta = connection.getMetaData();
            this.dbProductName = dbMeta.getDatabaseProductName().toUpperCase();
            setTxIsolation(connection);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return connection;
}

From source file:org.talend.cwm.db.connection.ConnectionUtils.java

/**
 * DOC xqliu Comment method "isPostgresql".
 * // www .j  a va2 s .com
 * @param connection
 * @return
 * @throws SQLException
 */
public static boolean isPostgresql(java.sql.Connection connection) throws SQLException {
    DatabaseMetaData metaData = connection.getMetaData();
    if (metaData != null) {
        String databaseProductName = metaData.getDatabaseProductName();
        if (databaseProductName != null) {
            return databaseProductName.toLowerCase().indexOf(DatabaseConstant.POSTGRESQL_PRODUCT_NAME) > -1;
        }
    }
    return false;
}

From source file:uk.ac.ebi.bioinvindex.utils.test.DBUnitTest.java

/**
 * Creates a new database connection to be used by DbUnit, used {@link #initDataSet()} and {@link #afterTestProcessing()}.
 * @throws SQLException /*from   w ww.  ja v  a2 s.  c  o m*/
 *
 */
protected IDatabaseConnection createDbUnitConnection() throws SQLException, DatabaseUnitException {
    IDatabaseConnection dbUnitCon = new DatabaseConnection(connection);
    DatabaseConfig config = dbUnitCon.getConfig();

    DatabaseMetaData dbmsMeta = connection.getMetaData();
    String dbmsName = dbmsMeta.getDatabaseProductName().toLowerCase();
    String dbmsCatalog = connection.getCatalog();
    if (dbmsCatalog == null)
        // Let's try with the user name
        dbmsCatalog = dbmsMeta.getUserName().toUpperCase();

    IDataTypeFactory dtf = new DefaultDataTypeFactory();
    if (dbmsName.contains("h2"))
        dtf = new H2DataTypeFactory();
    else if (dbmsName.contains("mysql"))
        dtf = new MySqlDataTypeFactory();
    else if (dbmsName.contains("oracle"))
        dtf = new Oracle10DataTypeFactory();
    else
        System.out.println("WARNING: Don't know which DBUnit DataType factory to use with '" + dbmsName
                + ", hope the default works");

    config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, dtf);

    return dbUnitCon;
}

From source file:com.flexive.core.storage.H2.H2StorageFactory.java

/**
 * {@inheritDoc}/*ww  w . java2  s .  co  m*/
 */
@Override
public boolean canHandle(DatabaseMetaData dbm) {
    try {
        return VENDOR.equals(dbm.getDatabaseProductName());
    } catch (SQLException e) {
        LOG.error(e);
        return false;
    }
}

From source file:org.apereo.portal.jdbc.DatabaseMetaDataImpl.java

/**
 * Gets meta data about the connection./*from   ww w  .  j  a va 2s  .  c om*/
 */
private void getMetaData(final Connection conn) {
    try {
        final DatabaseMetaData dmd = conn.getMetaData();

        this.databaseProductName = dmd.getDatabaseProductName();
        this.databaseProductVersion = dmd.getDatabaseProductVersion();
        this.driverName = dmd.getDriverName();
        this.driverVersion = dmd.getDriverVersion();
        this.userName = dmd.getUserName();
        this.dbUrl = dmd.getURL();
        this.dbmdSupportsOuterJoins = dmd.supportsOuterJoins();
    } catch (SQLException sqle) {
        LOG.error("Error getting database meta data.", sqle);
    }
}

From source file:net.certifi.audittablegen.AuditTableGen.java

/**
 * Validates the provided dataSource and gets a DataSourceDMR
 * object to manage database interaction.  Sets initialized flag
 * to true if initialization is successful.
 * @throws SQLException /*from  w w  w.  ja v a2s  .  com*/
 */
void initialize() throws SQLException {

    Connection connection = dataSource.getConnection();
    //Properties connectionProperties = connection.getClientInfo();
    DatabaseMetaData dmd = connection.getMetaData();

    logger.debug("DatabaseProduct: {}", dmd.getDatabaseProductName());

    try {
        catalog = connection.getCatalog();

        if (schema.isEmpty() || schema == null) {
            try {
                schema = connection.getSchema();
            } catch (AbstractMethodError e) {
                logger.error("Abstract method getSchema() not implemented", e);
                schema = "";
            }
        }
    } catch (SQLException e) {
        logger.error("Error getting catalog/schema", e);

    }

    if (dmd.getDriverName().toLowerCase().contains("postgresql")) {
        dmr = new PostgresqlDMR(dataSource, schema);
        //known dataSource with specific implementation requirements
        //ie PostgrresDMR, HsqldbDMR...            
    } else if (dmd.getDriverName().toLowerCase().contains("hsqldb")) {
        dmr = new HsqldbDMR(dataSource, schema);
        //known dataSource with specific implementation requirements
        //ie PostgrresDMR, HsqldbDMR...            
    } else {
        //generic implementation
        dmr = new GenericDMR(dataSource, schema);
        logger.info("attempting to run against unknown database product");
    }

    if (dmr != null) {
        this.initialized = true;
    }

    if (schema != null && !schema.isEmpty()) {
        dmr.setSchema(schema);

        if (dmr.getSchema() == null) {
            throw new RuntimeException("Schema could not be found.");
        }
    }

}

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

public void init(DatabasePlatformsRegistry databasePlatformsRegistry) {
    Connection conn = null;// w w  w.j a va2 s .  c o  m
    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:uk.ac.ebi.bioinvindex.utils.test.DBUnitTest.java

/**
 * Enables/disables the referential integrity checkings in the database.
 *
 * @param isset/* w  w w  . j  a  v  a2 s.c  o  m*/
 * @throws SQLException
 */
protected void setReferentialIntegrityCheckings(boolean isset) throws SQLException {

    String sql = null;

    DatabaseMetaData dbmsMeta = connection.getMetaData();
    String dbmsName = dbmsMeta.getDatabaseProductName().toLowerCase();
    String dbmsCatalog = connection.getCatalog();
    if (dbmsCatalog == null)
        // Let's try with the user name
        dbmsCatalog = dbmsMeta.getUserName().toUpperCase();

    log.debug("DBUnitTest.setReferentialIntegrityCheckings(), DBMS Name: '" + dbmsName + "' Catalog: '"
            + dbmsCatalog + "'");

    if (dbmsName.contains("h2"))
        sql = "SET REFERENTIAL_INTEGRITY " + isset;
    else if (dbmsName.contains("mysql"))
        sql = "set FOREIGN_KEY_CHECKS = " + (isset ? "1" : "0");
    else if (dbmsName.contains("oracle")) {
        // Oracle is quite messy...
        String sqlCs = "select css.*, decode(CONSTRAINT_TYPE, 'P', '0', 'C', '1', 'U', 2, 'R', '3', 1000) ctype "
                + "from sys.all_constraints css where owner = '" + dbmsCatalog + "' order by ctype "
                + (isset ? "ASC" : "DESC");

        ResultSet rs = connection.createStatement().executeQuery(sqlCs);
        Statement csDelStmt = connection.createStatement();
        while (rs.next()) {
            String sqlCsCmd = isset ? "enable" : "disable";
            String tbname = rs.getString("TABLE_NAME");
            String csname = rs.getString("CONSTRAINT_NAME");

            String sqlCsDel = "alter table " + dbmsCatalog + "." + tbname + " " + sqlCsCmd + " constraint "
                    + csname;
            log.debug("DBUnitTest, adding sql: " + sqlCsDel);
            csDelStmt.addBatch(sqlCsDel);
        }
        csDelStmt.executeBatch();
        return;
    }

    if (sql == null)
        throw new SQLException(
                "Don't know how to change referential integrity checks for the database: '" + dbmsName + "'");

    connection.createStatement().execute(sql);
}