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: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 2  s . 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.springframework.jdbc.core.metadata.GenericTableMetaDataProvider.java

@Override
public void initializeWithMetaData(DatabaseMetaData databaseMetaData) throws SQLException {
    try {//from w  w  w  . j a v a2  s .  c  o  m
        if (databaseMetaData.supportsGetGeneratedKeys()) {
            logger.debug("GetGeneratedKeys is supported");
            setGetGeneratedKeysSupported(true);
        } else {
            logger.debug("GetGeneratedKeys is not supported");
            setGetGeneratedKeysSupported(false);
        }
    } catch (SQLException ex) {
        if (logger.isWarnEnabled()) {
            logger.warn("Error retrieving 'DatabaseMetaData.getGeneratedKeys': " + ex.getMessage());
        }
    }
    try {
        String databaseProductName = databaseMetaData.getDatabaseProductName();
        if (this.productsNotSupportingGeneratedKeysColumnNameArray.contains(databaseProductName)) {
            if (logger.isDebugEnabled()) {
                logger.debug("GeneratedKeysColumnNameArray is not supported for " + databaseProductName);
            }
            setGeneratedKeysColumnNameArraySupported(false);
        } else {
            if (isGetGeneratedKeysSupported()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("GeneratedKeysColumnNameArray is supported for " + databaseProductName);
                }
                setGeneratedKeysColumnNameArraySupported(true);
            } else {
                setGeneratedKeysColumnNameArraySupported(false);
            }
        }
    } catch (SQLException ex) {
        if (logger.isWarnEnabled()) {
            logger.warn("Error retrieving 'DatabaseMetaData.getDatabaseProductName': " + ex.getMessage());
        }
    }

    try {
        this.databaseVersion = databaseMetaData.getDatabaseProductVersion();
    } catch (SQLException ex) {
        if (logger.isWarnEnabled()) {
            logger.warn("Error retrieving 'DatabaseMetaData.getDatabaseProductVersion': " + ex.getMessage());
        }
    }

    try {
        setStoresUpperCaseIdentifiers(databaseMetaData.storesUpperCaseIdentifiers());
    } catch (SQLException ex) {
        if (logger.isWarnEnabled()) {
            logger.warn("Error retrieving 'DatabaseMetaData.storesUpperCaseIdentifiers': " + ex.getMessage());
        }
    }

    try {
        setStoresLowerCaseIdentifiers(databaseMetaData.storesLowerCaseIdentifiers());
    } catch (SQLException ex) {
        if (logger.isWarnEnabled()) {
            logger.warn("Error retrieving 'DatabaseMetaData.storesLowerCaseIdentifiers': " + ex.getMessage());
        }
    }
}

From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java

public void setDocList(String checkpoint, String str_store_entry) {

    DatabaseMetaData dbm = null;
    Connection connection = null;

    logger.log(Level.FINEST, "Setting doclist " + checkpoint);
    logger.log(Level.FINEST, "Setting store_entry " + str_store_entry);
    try {//w  ww.j  a  v  a  2 s .co m

        connection = ds.getConnection();
        connection.setAutoCommit(true);

        dbm = connection.getMetaData();

        //logger.log(Level.FINE,"Base64 ENCODING...");
        String encode_entry = new String(
                org.apache.commons.codec.binary.Base64.encodeBase64(str_store_entry.getBytes()));
        str_store_entry = encode_entry;

        //logger.log(Level.FINE,"Setting store_entry ENCODED " + str_store_entry);

        if (dbm.getDatabaseProductName().equals("MySQL")) {
            //get the most recent row
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            String update_stmt = "select crawl_set from " + this.instance_table
                    + " where crawl_set=(select max(crawl_set) from " + this.instance_table + ")";
            logger.log(Level.FINE, "Getting lastentryp in db: " + update_stmt);
            ResultSet rs = statement.executeQuery(update_stmt);

            boolean ret_rows = rs.first();

            String last_entry_in_db = null;

            while (ret_rows) {
                BigDecimal crawl_set = rs.getBigDecimal("crawl_set");
                last_entry_in_db = crawl_set.toPlainString();
                ret_rows = rs.next();
            }

            logger.log(Level.FINER, "Last_Entry_in_Database " + last_entry_in_db);

            if (last_entry_in_db != null) {
                if (last_entry_in_db.startsWith(checkpoint)) {
                    //increment if in the same set
                    BigDecimal bd = new BigDecimal(last_entry_in_db);
                    bd = bd.add(new BigDecimal(".00001"));
                    logger.log(Level.INFO, "Adding to DBStore. Index Value: " + bd.toPlainString());
                    update_stmt = "insert into " + this.instance_table
                            + " (crawl_set,crawl_data) values (?,COMPRESS(?))";

                    PreparedStatement ps = connection.prepareStatement(update_stmt);
                    ps.setString(1, bd.toPlainString());
                    ps.setString(2, str_store_entry);
                    ps.executeUpdate();
                    ps.close();
                } else {
                    //otherwise add the the 0th row for this set
                    logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000");
                    update_stmt = "insert into " + this.instance_table
                            + " (crawl_set,crawl_data) values (?,COMPRESS(?))";
                    PreparedStatement ps = connection.prepareStatement(update_stmt);
                    ps.setString(1, checkpoint + ".00000");
                    ps.setString(2, str_store_entry);
                    ps.executeUpdate();
                    ps.close();
                }
            } else {
                logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000");
                update_stmt = "insert into " + this.instance_table
                        + " (crawl_set,crawl_data) values (?,COMPRESS(?))";
                PreparedStatement ps = connection.prepareStatement(update_stmt);
                ps.setString(1, checkpoint + ".00000");
                ps.setString(2, str_store_entry);
                ps.executeUpdate();
                ps.close();

            }

            rs.close();
            statement.close();
            connection.close();
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception initializing context Datasource " + ex);
        return;
    }
}

From source file:org.openbizview.util.Sgc001a.java

/**
 * Leer Datos de paises//from ww w  . jav  a  2 s.c om
 * @throws NamingException 
* @throws IOException 
 **/
public void select(int first, int pageSize, String sortField, Object filterValue)
        throws SQLException, ClassNotFoundException, NamingException {

    Context initContext = new InitialContext();
    DataSource ds = (DataSource) initContext.lookup(JNDI);
    con = ds.getConnection();
    //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno
    DatabaseMetaData databaseMetaData = con.getMetaData();
    productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin

    String validar = "1";
    String querycon = "SELECT BI_SGC014('" + login.toUpperCase() + "') AS VALIDAR FROM DUAL";

    //System.out.println(querycon);
    //System.out.println(JNDI);

    consulta.selectPntGenerica(querycon, JNDI);

    rows = consulta.getRows();
    tabla = consulta.getArray();
    //System.out.println(tabla[0][0]);   

    if (tabla[0][0].equals(validar)) {

        if (comp == null) {
            comp = " - ";
        }
        if (comp == "") {
            comp = " - ";
        }
        if (area == null) {
            area = " - ";
        }
        if (area == "") {
            area = " - ";
        }
        if (codigo == null) {
            codigo = " - ";
        }
        if (codigo == "") {
            codigo = " - ";
        }
        String[] veccomp = comp.split("\\ - ", -1);
        String[] vecarea = area.split("\\ - ", -1);
        String[] veccodigo = codigo.split("\\ - ", -1);

        //Consulta paginada
        String query = "SELECT * FROM";
        query += "(select query.*, rownum as rn from";
        query += "(SELECT A.COMP, A.AREA, A.CODIGO, A.TIPVAL, TO_CHAR(A.FECCAM,'DD/MM/YYYY') AS FECCAM, A.META, B.DESCR AS DESC1, C.DESCR AS DESC2, D.NOMIND AS DESC3, E.DESCR AS DESC4, A.REGIST, A.RESMET ";
        query += "FROM SGC001A A, SGC005 B, SGC006 C, SGC001 D, TUBDER11 E ";
        query += "WHERE A.COMP = B.CODIGO ";
        query += "AND A.COMP = C.COMP ";
        query += "AND A.AREA = C.CODIGO ";
        query += "AND A.COMP = D.COMP ";
        query += "AND A.AREA = D.AREA ";
        query += "AND A.CODIGO = D.CODIGO ";
        query += "AND A.TIPVAL = E.CODIGO ";
        query += "AND TRIM(A.COMP) LIKE TRIM('%" + veccomp[0] + "%') ";
        query += "AND TRIM(A.AREA) LIKE TRIM('%" + vecarea[0] + "%') ";
        query += "AND TRIM(A.CODIGO) LIKE TRIM('%" + veccodigo[0] + "%') ";
        query += " AND TRIM(D.CODIGO)||TRIM(D.NOMIND) LIKE TRIM('%" + ((String) filterValue).toUpperCase()
                + "%')";
        query += "GROUP BY A.COMP, A.AREA, A.CODIGO, A.TIPVAL, A.FECCAM, A.META, B.DESCR, C.DESCR, D.NOMIND, E.DESCR, A.REGIST, A.RESMET ";
        query += "ORDER BY A.COMP, A.AREA, A.CODIGO, A.FECCAM, A.REGIST ";
        query += ")query ) ";
        query += " WHERE ROWNUM <=" + pageSize;
        query += " AND rn > (" + first + ")";

        pstmt = con.prepareStatement(query);
        //System.out.println(query);
        //System.out.println("***ADMINISTRADOR***");

        r = pstmt.executeQuery();

        while (r.next()) {
            Sgc001a select = new Sgc001a();
            select.setZcomp(r.getString(1) + " - " + r.getString(7));
            select.setZarea(r.getString(2) + " - " + r.getString(8));
            select.setZcodigo(r.getString(3) + " - " + r.getString(9));
            select.setZtvalm(r.getString(4) + " - " + r.getString(10));
            select.setZfeccam(r.getString(5));
            select.setZmeta(r.getString(6));
            select.setZdesc1(r.getString(7));
            select.setZdesc2(r.getString(8));
            select.setZdesc3(r.getString(9));
            select.setZdesc4(r.getString(10));
            select.setZdelete(
                    r.getString(1) + "" + r.getString(2) + "" + r.getString(3) + "" + r.getString(11));
            select.setZregist(r.getString(11));
            select.setZresmet(r.getString(12));

            //Agrega la lista
            list.add(select);
        }
        //Cierra las conecciones
        pstmt.close();
        con.close();

    } else {

        if (comp == null) {
            comp = " - ";
        }
        if (comp == "") {
            comp = " - ";
        }
        if (area == null) {
            area = " - ";
        }
        if (area == "") {
            area = " - ";
        }
        if (codigo == null) {
            codigo = " - ";
        }
        if (codigo == "") {
            codigo = " - ";
        }
        String[] veccomp = comp.split("\\ - ", -1);
        String[] vecarea = area.split("\\ - ", -1);
        String[] veccodigo = codigo.split("\\ - ", -1);

        String query = " SELECT";
        query += " TOT.*";
        query += " FROM (select ";
        query += "       DISTINCT RES.*";
        query += "       from (SELECT  ";
        query += "             A.COMP, A.AREA, A.CODIGO, A.TIPVAL, TO_CHAR(A.FECCAM,'DD/MM/YYYY') AS FECCAM, A.META, B.DESCR AS DESC1, C.DESCR AS DESC2, ";
        query += "             D.NOMIND AS DESC3, E.DESCR AS DESC4, A.REGIST, A.RESMET ";
        query += "             FROM ";
        query += "             SGC001A A, SGC005 B, SGC006 C, SGC001 D, TUBDER11 E, SGC009 F";
        query += "             WHERE ";
        query += "             A.COMP = B.CODIGO ";
        query += "             AND A.COMP = C.COMP ";
        query += "             AND A.AREA = C.CODIGO ";
        query += "             AND A.COMP = D.COMP ";
        query += "             AND A.AREA = D.AREA ";
        query += "             AND A.CODIGO = D.CODIGO ";
        query += "             AND A.TIPVAL = E.CODIGO ";
        query += "             AND A.COMP = F.COMP";
        query += "             AND A.AREA = F.AREA";
        query += "             AND A.CODIGO = F.INDICA";
        query += "             AND F.CODUSER = '" + login.toUpperCase() + "'";
        query += "             AND TRIM(D.CODIGO)||TRIM(D.NOMIND) LIKE TRIM('%"
                + ((String) filterValue).toUpperCase() + "%')";
        query += "             UNION ALL";
        query += "             SELECT  ";
        query += "             A.COMP, A.AREA, A.CODIGO, A.TIPVAL, TO_CHAR(A.FECCAM,'DD/MM/YYYY') AS FECCAM, A.META, B.DESCR AS DESC1, C.DESCR AS DESC2, ";
        query += "             D.NOMIND AS DESC3, E.DESCR AS DESC4, A.REGIST, A.RESMET ";
        query += "             FROM ";
        query += "             SGC001A A, SGC005 B, SGC006 C, SGC001 D, TUBDER11 E ";
        query += "             WHERE ";
        query += "             A.COMP = B.CODIGO ";
        query += "             AND A.COMP = C.COMP ";
        query += "             AND A.AREA = C.CODIGO ";
        query += "             AND A.COMP = D.COMP ";
        query += "             AND A.AREA = D.AREA ";
        query += "             AND A.CODIGO = D.CODIGO ";
        query += "             AND A.TIPVAL = E.CODIGO ";
        query += "             AND TRIM(D.CODIGO)||TRIM(D.NOMIND) LIKE TRIM('%"
                + ((String) filterValue).toUpperCase() + "%')";
        query += "             AND A.COMP||A.AREA IN (SELECT COMP||AREA FROM SGC008 WHERE CODUSER = '"
                + login.toUpperCase() + "' AND DUEPRO = '1')";
        query += "             ) RES";
        query += "       WHERE ";
        query += "       TRIM(RES.COMP) LIKE TRIM('%" + veccomp[0] + "%') ";
        query += "       AND TRIM(RES.AREA) LIKE TRIM('%" + vecarea[0] + "%') ";
        query += "       AND TRIM(RES.CODIGO) LIKE TRIM('%" + veccodigo[0] + "%') ORDER BY 1,2,3) TOT";
        query += " WHERE      ";
        query += " ROWNUM <=" + pageSize;
        query += " AND ROWNUM > (" + first + ")";

        pstmt = con.prepareStatement(query);
        //System.out.println(query);
        //System.out.println("***NO ADMINISTRADOR***");

        r = pstmt.executeQuery();

        while (r.next()) {
            Sgc001a select = new Sgc001a();
            select.setZcomp(r.getString(1) + " - " + r.getString(7));
            select.setZarea(r.getString(2) + " - " + r.getString(8));
            select.setZcodigo(r.getString(3) + " - " + r.getString(9));
            select.setZtvalm(r.getString(4) + " - " + r.getString(10));
            select.setZfeccam(r.getString(5));
            select.setZmeta(r.getString(6));
            select.setZdesc1(r.getString(7));
            select.setZdesc2(r.getString(8));
            select.setZdesc3(r.getString(9));
            select.setZdesc4(r.getString(10));
            select.setZdelete(
                    r.getString(1) + "" + r.getString(2) + "" + r.getString(3) + "" + r.getString(11));
            select.setZregist(r.getString(11));
            select.setZresmet(r.getString(12));

            //Agrega la lista
            list.add(select);
        }
        //Cierra las conecciones
        pstmt.close();
        con.close();

    }
}

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

/**
 *
 * @param ds A DataSource//from w  w w.ja v  a 2  s.  c om
 *
 * @param schema Name of schema to perform operations upon.
 * @throws SQLException
 */
GenericDMR(DataSource ds, String schema) throws SQLException {

    dataSource = ds;
    Connection conn = ds.getConnection();
    DatabaseMetaData dmd = conn.getMetaData();
    databaseProduct = dmd.getDatabaseProductName();
    //idMetaData = new IdentifierMetaData();

    //storing this data for potential future use.
    //not using it for anything currently
    //idMetaData.setStoresLowerCaseIds(dmd.storesLowerCaseIdentifiers());
    //idMetaData.setStoresMixedCaseIds(dmd.storesMixedCaseIdentifiers());
    //idMetaData.setStoresUpperCaseIds(dmd.storesUpperCaseIdentifiers());

    unverifiedSchema = schema;

    conn.close();

}

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.executequery.gui.importexport.AbstractImportExportWorker.java

private int fetchSizeForDatabaseProduct(DatabaseMetaData metaData) throws SQLException {

    // we only care about mysql right now which needs Integer.MIN_VALUE
    // to provide row-by-row return on the result set cursor
    // otherwise default to 1000 row fetch size... 

    if (metaData.getDatabaseProductName().toUpperCase().contains("MYSQL")) {

        return Integer.MIN_VALUE;
    }//from   w  w w .j  a  v a  2s  .c o m

    return 10000;
}

From source file:org.glite.security.voms.admin.persistence.deployer.SchemaDeployer.java

private boolean isOracleBackend() {

    Session s = HibernateFactory.getSession();
    s.beginTransaction();/*  w ww .  j  a va 2 s .  co m*/

    DatabaseMetaData dbMetadata = null;
    String dbProductName = null;

    try {

        dbMetadata = getDatabaseMetadata(s);
        dbProductName = dbMetadata.getDatabaseProductName();

    } catch (HibernateException e) {

        log.error("Hibernate error accessing database metadata from Hibernate connection!", e);
        System.exit(-1);

    } catch (SQLException e) {

        log.error("SQL error while accessing database metadata from Hibernate connection!", e);
        System.exit(-1);

    }

    log.debug("Detected database: " + dbProductName);
    return dbProductName.trim().equals(ORACLE_PRODUCT_NAME);

}

From source file:com.raise.orgs.impl.cfg.ProcessEngineConfigurationImpl.java

public void initDatabaseType() {
    Connection connection = null;
    try {/*w ww .  jav  a 2 s  . com*/
        connection = dataSource.getConnection();
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String databaseProductName = databaseMetaData.getDatabaseProductName();
        log.debug("database product name: '{}'", databaseProductName);
        databaseType = databaseTypeMappings.getProperty(databaseProductName);
        if (databaseType == null) {
            throw new ActivitiException(
                    "couldn't deduct database type from database product name '" + databaseProductName + "'");
        }
        log.debug("using database type: {}", databaseType);

    } catch (SQLException e) {
        log.error("Exception while initializing Database connection", e);
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            log.error("Exception while closing the Database connection", e);
        }
    }
}

From source file:org.openbizview.util.Bvt002.java

/**
 * Leer registros en la tabla//from ww  w  .  j  a va 2s .c  o  m
 * @throws NamingException 
 * @throws IOException 
 **/
public void counter(Object filterValue) throws SQLException, NamingException {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);
        con = ds.getConnection();
        //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno
        DatabaseMetaData databaseMetaData = con.getMetaData();
        productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin

        String query = "";

        switch (productName) {
        case "Oracle":
            query = "SELECT count_bvt002('" + ((String) filterValue).toUpperCase() + "') from dual";
            break;
        case "PostgreSQL":
            query = "SELECT count_bvt002('" + ((String) filterValue).toUpperCase() + "')";
            break;
        case "Microsoft SQL Server":
            query = "SELECT DBO.count_bvt002('" + ((String) filterValue).toUpperCase() + "')";
            break;
        }

        pstmt = con.prepareStatement(query);
        //System.out.println(query);

        r = pstmt.executeQuery();

        while (r.next()) {
            rows = r.getInt(1);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    //Cierra las conecciones
    pstmt.close();
    con.close();
    r.close();

}