Example usage for java.sql DatabaseMetaData supportsGetGeneratedKeys

List of usage examples for java.sql DatabaseMetaData supportsGetGeneratedKeys

Introduction

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

Prototype

boolean supportsGetGeneratedKeys() throws SQLException;

Source Link

Document

Retrieves whether auto-generated keys can be retrieved after a statement has been executed

Usage

From source file:Main.java

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

    DatabaseMetaData md = conn.getMetaData();
    System.out.println("supportsGetGeneratedKeys - " + md.supportsGetGeneratedKeys());

    conn.close();//from w  w  w  .ja va  2s .  c o m
}

From source file:DeliverWork.java

private static String saveIntoWeed(RemoteFile remoteFile, String projectId)
        throws SQLException, UnsupportedEncodingException {
    String url = "http://59.215.226.174/WebDiskServerDemo/doc?doc_id="
            + URLEncoder.encode(remoteFile.getFileId(), "utf-8");
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String res = "";
    try {//from w  w w.  ja va2s .  c  om
        httpClient = HttpClients.createSystem();
        // http(get?)
        HttpGet httpget = new HttpGet(url);
        response = httpClient.execute(httpget);
        HttpEntity result = response.getEntity();
        String fileName = remoteFile.getFileName();
        FileHandleStatus fileHandleStatus = getFileTemplate().saveFileByStream(fileName,
                new ByteArrayInputStream(EntityUtils.toByteArray(result)));
        System.out.println(fileHandleStatus);
        File file = new File();
        if (result != null && result.getContentType() != null && result.getContentType().getValue() != null) {
            file.setContentType(result.getContentType().getValue());
        } else {
            file.setContentType("application/error");
        }
        file.setDataId(Integer.parseInt(projectId));
        file.setName(fileName);
        if (fileName.contains(".bmp") || fileName.contains(".jpg") || fileName.contains(".jpeg")
                || fileName.contains(".png") || fileName.contains(".gif")) {
            file.setType(1);
        } else if (fileName.contains(".doc") || fileName.contains(".docx")) {
            file.setType(2);
        } else if (fileName.contains(".xlsx") || fileName.contains("xls")) {
            file.setType(3);
        } else if (fileName.contains(".pdf")) {
            file.setType(4);
        } else {
            file.setType(5);
        }
        String accessUrl = "/" + fileHandleStatus.getFileId().replaceAll(",", "/").concat("/").concat(fileName);
        file.setUrl(accessUrl);
        file.setSize(fileHandleStatus.getSize());
        file.setPostTime(new java.util.Date());
        file.setStatus(0);
        file.setEnumValue(findFileType(remoteFile.getFileType()));
        file.setResources(1);
        //            JdbcFactory jdbcFactoryChanye=new JdbcFactory("jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8","root","111111","com.mysql.jdbc.Driver");
        //            Connection connection = jdbcFactoryChanye.getConnection();
        DatabaseMetaData dmd = connection.getMetaData();
        PreparedStatement ps = connection.prepareStatement(insertFile, new String[] { "ID" });
        ps.setString(1, sdf.format(file.getPostTime()));
        ps.setInt(2, file.getType());
        ps.setString(3, file.getEnumValue());
        ps.setInt(4, file.getDataId());
        ps.setString(5, file.getUrl());
        ps.setString(6, file.getName());
        ps.setString(7, file.getContentType());
        ps.setLong(8, file.getSize());
        ps.setInt(9, file.getStatus());
        ps.setInt(10, file.getResources());
        ps.executeUpdate();
        if (dmd.supportsGetGeneratedKeys()) {
            ResultSet rs = ps.getGeneratedKeys();
            while (rs.next()) {
                System.out.println(rs.getLong(1));
            }
        }
        ps.close();
        res = "success";
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return res;
}

From source file:it.greenvulcano.gvesb.j2ee.db.connections.impl.DriverPoolConnectionBuilder.java

public Connection getConnection() throws GVDBException {
    try {/* ww w  . j a  va2  s  .co  m*/
        Connection conn = dataSource.getConnection();
        if (debugJDBCConn) {
            logger.debug("Created JDBC Connection [" + name + "]: [" + conn + "]");
            if (isFirst) {
                isFirst = false;
                DatabaseMetaData dbmd = conn.getMetaData();

                logger.debug("=====  Database info =====");
                logger.debug("DatabaseProductName: " + dbmd.getDatabaseProductName());
                logger.debug("DatabaseProductVersion: " + dbmd.getDatabaseProductVersion());
                logger.debug("DatabaseMajorVersion: " + dbmd.getDatabaseMajorVersion());
                logger.debug("DatabaseMinorVersion: " + dbmd.getDatabaseMinorVersion());
                logger.debug("=====  Driver info =====");
                logger.debug("DriverName: " + dbmd.getDriverName());
                logger.debug("DriverVersion: " + dbmd.getDriverVersion());
                logger.debug("DriverMajorVersion: " + dbmd.getDriverMajorVersion());
                logger.debug("DriverMinorVersion: " + dbmd.getDriverMinorVersion());
                logger.debug("=====  JDBC/DB attributes =====");
                if (dbmd.supportsGetGeneratedKeys())
                    logger.debug("Supports getGeneratedKeys(): true");
                else
                    logger.debug("Supports getGeneratedKeys(): false");
            }
        }

        return conn;
    } catch (Exception exc) {
        throw new GVDBException("DriverPoolConnectionBuilder - Error while creating Connection[" + name + "]",
                exc);
    }
}

From source file:com.qualogy.qafe.business.resource.rdb.query.enhancer.SQLQueryEnhancer.java

public Query enhance(Query query, DatabaseMetaData databaseMetaData) throws EnhancementFailedException {
    SQLQuery sqlQuery = (SQLQuery) query;

    ResultSet resultSet = null;//from  ww  w. ja  v  a  2s .  com

    try {
        if (StringUtils.isBlank(sqlQuery.getSqlAsAttribute()) && StringUtils.isBlank(sqlQuery.getSqlAsText())
                && StringUtils.isNotBlank(sqlQuery.getTable())) {
            // The Oracle database stores its table names as Upper-Case,
            // if you pass a table name in lowercase characters, it will not work.
            // MySQL database does not care if table name is uppercase/lowercase.
            //
            // TODO:check if there is a way to catch table data
            // TODO: dialect needed for upper/lowercase
            String userName = databaseMetaData.getUserName();
            resultSet = databaseMetaData.getTables(null, null, sqlQuery.getTable().toUpperCase(), null);

            String tableSchema = null;

            // Knowing schema name is not necessary but we gain performance
            // by using it during retrieving meta data.
            while (resultSet.next() && (null != userName)) {
                // some vendors like MySQL do not provide schema name
                // that's why we have to check whether the schema name is "null"
                if ((null != resultSet.getString("TABLE_SCHEM"))
                        && resultSet.getString("TABLE_SCHEM").equals(userName)) {
                    tableSchema = userName;

                    break;
                }

                // TABLE_TYPE
            }

            try {
                sqlQuery.getMetaData().setSupportsGetGeneratedKeys(databaseMetaData.supportsGetGeneratedKeys());
            } catch (AbstractMethodError e) {
                LOG.log(Level.WARNING,
                        "On the database driver there is no support for Metadata reading (sqlquery: "
                                + sqlQuery.getId() + ")",
                        e);
            }

            // if you pass null values for the first two parameters, then
            // it might take too long to return the result.
            resultSet = databaseMetaData.getPrimaryKeys(null, tableSchema, sqlQuery.getTable().toUpperCase());

            while (resultSet.next()) {
                sqlQuery.getMetaData().addPrimaryKey(resultSet.getString("COLUMN_NAME"));
            }

            // if no primarykeys found on a table, an update statement cannot be generated
            // so the query will be marked as error containing.
            sqlQuery.validate();
        }
    } catch (SQLException e) {
        throw new EnhancementFailedException(e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new EnhancementFailedException(e);
            }
        }
    }

    return sqlQuery;
}

From source file:org.acmsl.queryj.tools.handlers.DatabaseMetaDataLoggingHandler.java

/**
 * Handles given information./*  w  w  w  . j  a  v a 2  s.  com*/
 * @param metaData the database metadata.
 * @return <code>true</code> if the chain should be stopped.
 * @throws QueryJBuildException if the metadata cannot be logged.
 */
protected boolean handle(@NotNull final DatabaseMetaData metaData) throws QueryJBuildException {
    final boolean result = false;

    @Nullable
    Log t_Log = null;

    try {
        t_Log = UniqueLogFactory.getLog(DatabaseMetaDataLoggingHandler.class);

        if (t_Log != null) {
            t_Log.debug("Numeric functions:" + metaData.getNumericFunctions());

            t_Log.debug("String functions:" + metaData.getStringFunctions());

            t_Log.debug("System functions:" + metaData.getSystemFunctions());

            t_Log.debug("Time functions:" + metaData.getTimeDateFunctions());

            t_Log.debug("insertsAreDetected(TYPE_FORWARD_ONLY):"
                    + metaData.insertsAreDetected(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("insertsAreDetected(TYPE_SCROLL_INSENSITIVE):"
                    + metaData.insertsAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("insertsAreDetected(TYPE_SCROLL_SENS):"
                    + metaData.insertsAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("isCatalogAtStart():" + metaData.isCatalogAtStart());

            t_Log.debug("isReadOnly():" + metaData.isReadOnly());

            /*
             * Fails for MySQL with a java.lang.AbstractMethodError 
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.locatorsUpdateCopy()
             t_Log.debug(
               "locatorsUpdateCopy():"
             + metaData.locatorsUpdateCopy());
             */

            t_Log.debug("nullPlusNonNullIsNull():" + metaData.nullPlusNonNullIsNull());

            t_Log.debug("nullsAreSortedAtEnd():" + metaData.nullsAreSortedAtEnd());

            t_Log.debug("nullsAreSortedAtStart():" + metaData.nullsAreSortedAtStart());

            t_Log.debug("nullsAreSortedHigh():" + metaData.nullsAreSortedHigh());

            t_Log.debug("nullsAreSortedLow():" + metaData.nullsAreSortedLow());

            t_Log.debug("othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("othersDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("othersDeletesAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("othersInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("othersUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.othersUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("ownDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.ownDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("ownDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("ownDeletesAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("ownInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.ownInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("ownInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("ownInsertsAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("ownUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.ownUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("storesLowerCaseIdentifiers():" + metaData.storesLowerCaseIdentifiers());

            t_Log.debug("storesLowerCaseQuotedIdentifiers():" + metaData.storesLowerCaseQuotedIdentifiers());

            t_Log.debug("storesMixedCaseIdentifiers():" + metaData.storesMixedCaseIdentifiers());

            t_Log.debug("storesMixedCaseQuotedIdentifiers():" + metaData.storesMixedCaseQuotedIdentifiers());

            t_Log.debug("storesUpperCaseIdentifiers():" + metaData.storesUpperCaseIdentifiers());

            t_Log.debug("storesUpperCaseQuotedIdentifiers():" + metaData.storesUpperCaseQuotedIdentifiers());

            t_Log.debug("supportsAlterTableWithAddColumn():" + metaData.supportsAlterTableWithAddColumn());

            t_Log.debug("supportsAlterTableWithDropColumn():" + metaData.supportsAlterTableWithDropColumn());

            t_Log.debug("supportsANSI92EntryLevelSQL():" + metaData.supportsANSI92EntryLevelSQL());

            t_Log.debug("supportsANSI92FullSQL():" + metaData.supportsANSI92FullSQL());

            t_Log.debug("supportsANSI92IntermediateSQL():" + metaData.supportsANSI92IntermediateSQL());

            t_Log.debug("supportsBatchUpdates():" + metaData.supportsBatchUpdates());

            t_Log.debug(
                    "supportsCatalogsInDataManipulation():" + metaData.supportsCatalogsInDataManipulation());

            t_Log.debug(
                    "supportsCatalogsInIndexDefinitions():" + metaData.supportsCatalogsInIndexDefinitions());

            t_Log.debug("supportsCatalogsInPrivilegeDefinitions():"
                    + metaData.supportsCatalogsInPrivilegeDefinitions());

            t_Log.debug("supportsCatalogsInProcedureCalls():" + metaData.supportsCatalogsInProcedureCalls());

            t_Log.debug(
                    "supportsCatalogsInTableDefinitions():" + metaData.supportsCatalogsInTableDefinitions());

            t_Log.debug("supportsColumnAliasing():" + metaData.supportsColumnAliasing());

            t_Log.debug("supportsConvert():" + metaData.supportsConvert());

            t_Log.debug("supportsCoreSQLGrammar():" + metaData.supportsCoreSQLGrammar());

            t_Log.debug("supportsCorrelatedSubqueries():" + metaData.supportsCorrelatedSubqueries());

            t_Log.debug("supportsDataDefinitionAndDataManipulationTransactions():"
                    + metaData.supportsDataDefinitionAndDataManipulationTransactions());

            t_Log.debug("supportsDataManipulationTransactionsOnly():"
                    + metaData.supportsDataManipulationTransactionsOnly());

            t_Log.debug("supportsDifferentTableCorrelationNames():"
                    + metaData.supportsDifferentTableCorrelationNames());

            t_Log.debug("supportsExpressionsInOrderBy():" + metaData.supportsExpressionsInOrderBy());

            t_Log.debug("supportsExtendedSQLGrammar():" + metaData.supportsExtendedSQLGrammar());

            t_Log.debug("supportsFullOuterJoins():" + metaData.supportsFullOuterJoins());

            String t_strSupportsGetGeneratedKeys = Boolean.FALSE.toString();

            try {
                t_strSupportsGetGeneratedKeys = "" + metaData.supportsGetGeneratedKeys();
            } catch (@NotNull final SQLException sqlException) {
                t_strSupportsGetGeneratedKeys += sqlException.getMessage();
            }

            t_Log.debug("supportsGetGeneratedKeys():" + t_strSupportsGetGeneratedKeys);

            t_Log.debug("supportsGroupBy():" + metaData.supportsGroupBy());

            t_Log.debug("supportsGroupByBeyondSelect():" + metaData.supportsGroupByBeyondSelect());

            t_Log.debug("supportsGroupByUnrelated():" + metaData.supportsGroupByUnrelated());

            t_Log.debug("supportsIntegrityEnhancementFacility():"
                    + metaData.supportsIntegrityEnhancementFacility());

            t_Log.debug("supportsLikeEscapeClause():" + metaData.supportsLikeEscapeClause());

            t_Log.debug("supportsLimitedOuterJoins():" + metaData.supportsLimitedOuterJoins());

            t_Log.debug("supportsMinimumSQLGrammar():" + metaData.supportsMinimumSQLGrammar());

            t_Log.debug("supportsMixedCaseIdentifiers():" + metaData.supportsMixedCaseIdentifiers());

            t_Log.debug(
                    "supportsMixedCaseQuotedIdentifiers():" + metaData.supportsMixedCaseQuotedIdentifiers());

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsMultipleOpenResults()
             t_Log.debug(
               "supportsMultipleOpenResults():"
             + metaData.supportsMultipleOpenResults());
             */

            t_Log.debug("supportsMultipleResultSets():" + metaData.supportsMultipleResultSets());

            t_Log.debug("supportsMultipleTransactions():" + metaData.supportsMultipleTransactions());

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsNamedParameters()
             t_Log.debug(
               "supportsNamedParameters():"
             + metaData.supportsNamedParameters());
             */

            t_Log.debug("supportsNonNullableColumns():" + metaData.supportsNonNullableColumns());

            t_Log.debug("supportsOpenCursorsAcrossCommit():" + metaData.supportsOpenCursorsAcrossCommit());

            t_Log.debug("supportsOpenCursorsAcrossRollback():" + metaData.supportsOpenCursorsAcrossRollback());

            t_Log.debug(
                    "supportsOpenStatementsAcrossCommit():" + metaData.supportsOpenStatementsAcrossCommit());

            t_Log.debug("supportsOpenStatementsAcrossRollback():"
                    + metaData.supportsOpenStatementsAcrossRollback());

            t_Log.debug("supportsOrderByUnrelated():" + metaData.supportsOrderByUnrelated());

            t_Log.debug("supportsOuterJoins():" + metaData.supportsOuterJoins());

            t_Log.debug("supportsPositionedDelete():" + metaData.supportsPositionedDelete());

            t_Log.debug("supportsPositionedUpdate():" + metaData.supportsPositionedUpdate());

            t_Log.debug("supportsResultSetConcurrency(TYPE_FORWARD_ONLY,CONCUR_READ_ONLY):" + metaData
                    .supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY));

            t_Log.debug("supportsResultSetConcurrency(TYPE_FORWARD_ONLY,CONCUR_UPDATABLE):" + metaData
                    .supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE));

            t_Log.debug("supportsResultSetConcurrency(TYPE_SCROLL_INSENSITIVE,CONCUR_READ_ONLY):"
                    + metaData.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE,
                            ResultSet.CONCUR_READ_ONLY));

            t_Log.debug("supportsResultSetConcurrency(TYPE_SCROLL_INSENSITIVE,CONCUR_UPDATABLE):"
                    + metaData.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE,
                            ResultSet.CONCUR_UPDATABLE));

            t_Log.debug("supportsResultSetConcurrency(TYPE_SCROLL_SENSITIVE,CONCUR_READ_ONLY):" + metaData
                    .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY));

            t_Log.debug("supportsResultSetConcurrency(TYPE_SCROLL_SENSITIVE,CONCUR_UPDATABLE):" + metaData
                    .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE));

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsResultSetHoldability()
             t_Log.debug(
               "supportsResultSetHoldability("
             +     "HOLD_CURSORS_OVER_COMMIT):"
             + metaData.supportsResultSetHoldability(
             ResultSet.HOLD_CURSORS_OVER_COMMIT));
                    
             t_Log.debug(
               "supportsResultSetHoldability("
             +     "CLOSE_CURSORS_AT_COMMIT):"
             + metaData.supportsResultSetHoldability(
             ResultSet.CLOSE_CURSORS_AT_COMMIT));
             */

            t_Log.debug("supportsResultSetType(TYPE_FORWARD_ONLY):"
                    + metaData.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("supportsResultSetType(TYPE_SCROLL_SENSITIVE):"
                    + metaData.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE));

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsSavePoints()
             t_Log.debug(
               "supportsSavepoints():"
             + metaData.supportsSavepoints());
             */

            t_Log.debug("supportsSchemasInDataManipulation():" + metaData.supportsSchemasInDataManipulation());

            t_Log.debug("supportsSchemasInIndexDefinitions():" + metaData.supportsSchemasInIndexDefinitions());

            t_Log.debug("supportsSchemasInPrivilegeDefinitions():"
                    + metaData.supportsSchemasInPrivilegeDefinitions());

            t_Log.debug("supportsSchemasInProcedureCalls():" + metaData.supportsSchemasInProcedureCalls());

            t_Log.debug("supportsSchemasInTableDefinitions():" + metaData.supportsSchemasInTableDefinitions());

            t_Log.debug("supportsSelectForUpdate():" + metaData.supportsSelectForUpdate());

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsStatementPooling()
             t_Log.debug(
               "supportsStatementPooling():"
             + metaData.supportsStatementPooling());
            */

            t_Log.debug("supportsStoredProcedures():" + metaData.supportsStoredProcedures());

            t_Log.debug("supportsSubqueriesInComparisons():" + metaData.supportsSubqueriesInComparisons());

            t_Log.debug("supportsSubqueriesInExists():" + metaData.supportsSubqueriesInExists());

            t_Log.debug("supportsSubqueriesInIns():" + metaData.supportsSubqueriesInIns());

            t_Log.debug("supportsSubqueriesInQuantifieds():" + metaData.supportsSubqueriesInQuantifieds());

            t_Log.debug("supportsTableCorrelationNames():" + metaData.supportsTableCorrelationNames());

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_NONE):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE));

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_READ_COMMITTED):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_READ_UNCOMMITTED):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_REPEATABLE_READ):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));

            t_Log.debug("supportsTransactions():" + metaData.supportsTransactions());

            t_Log.debug("supportsUnion():" + metaData.supportsUnion());

            t_Log.debug("supportsUnionAll():" + metaData.supportsUnionAll());

            t_Log.debug("updatesAreDetected(TYPE_FORWARD_ONLY):"
                    + metaData.updatesAreDetected(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("updatesAreDetected(TYPE_SCROLL_INSENSITIVE):"
                    + metaData.updatesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("updatesAreDetected(" + "TYPE_SCROLL_SENS):"
                    + metaData.updatesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("usesLocalFilePerTable():" + metaData.usesLocalFilePerTable());

            t_Log.debug("usesLocalFiles():" + metaData.usesLocalFiles());
        }
    } catch (@NotNull final SQLException sqlException) {
        t_Log.error("Database metadata request failed.", sqlException);
    }

    return result;
}

From source file:org.apache.ode.bpel.extvar.jdbc.JdbcExternalVariableModule.java

public void configure(QName pid, String extVarId, Element config) throws ExternalVariableModuleException {
    EVarId evarId = new EVarId(pid, extVarId);
    DataSource ds = null;/*w w w .j  a  v a2s .co m*/

    Element jndiDs = DOMUtils.findChildByName(config, new QName(JDBC_NS, "datasource-jndi"));
    Element jndiRef = DOMUtils.findChildByName(config, new QName(JDBC_NS, "datasource-ref"));
    Element initMode = DOMUtils.findChildByName(config, new QName(JDBC_NS, "init-mode"));
    if (jndiRef != null) {
        String refname = jndiRef.getTextContent().trim();
        ds = _dataSources.get(refname);
        if (ds == null)
            throw new ExternalVariableModuleException(
                    "Data source reference \"" + refname + "\" not found for external variable " + evarId
                            + "; make sure to register the data source with the engine!");
    } else if (jndiDs != null) {
        String name = jndiDs.getTextContent().trim();
        Object dsCandidate;
        InitialContext ctx;
        try {
            ctx = new InitialContext();
        } catch (Exception ex) {
            throw new ExternalVariableModuleException(
                    "Unable to access JNDI context for external variable " + evarId, ex);
        }

        try {
            dsCandidate = ctx.lookup(name);
        } catch (Exception ex) {
            throw new ExternalVariableModuleException("Lookup of data source for " + evarId + "  failed.", ex);
        } finally {
            try {
                ctx.close();
            } catch (NamingException e) {
                /* ignore */ }
        }

        if (dsCandidate == null)
            throw new ExternalVariableModuleException("Data source \"" + name + "\" not found in JNDI!");

        if (!(dsCandidate instanceof DataSource))
            throw new ExternalVariableModuleException(
                    "JNDI object \"" + name + "\" does not implement javax.sql.DataSource");

        ds = (DataSource) dsCandidate;
    }

    if (ds == null) {
        throw new ExternalVariableModuleException(
                "No valid data source configuration for JDBC external varible " + evarId);
    }

    Connection conn = null;
    DatabaseMetaData metaData;
    try {
        conn = ds.getConnection();
        metaData = conn.getMetaData();
    } catch (Exception ex) {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            // ignore
        }
        throw new ExternalVariableModuleException(
                "Unable to open database connection for external variable " + evarId, ex);
    }

    try {
        DbExternalVariable dbev = new DbExternalVariable(evarId, ds);
        if (initMode != null)
            try {
                dbev._initType = InitType.valueOf(initMode.getTextContent().trim());
            } catch (Exception ex) {
                throw new ExternalVariableModuleException(
                        "Invalid <init-mode> value: " + initMode.getTextContent().trim());
            }

        Element tableName = DOMUtils.findChildByName(config, new QName(JDBC_NS, "table"));
        if (tableName == null || tableName.getTextContent().trim().equals(""))
            throw new ExternalVariableModuleException("Must specify <table> for external variable " + evarId);
        String table = tableName.getTextContent().trim();
        String schema = null;
        if (table.indexOf('.') != -1) {
            schema = table.substring(0, table.indexOf('.'));
            table = table.substring(table.indexOf('.') + 1);
        }

        if (metaData.storesLowerCaseIdentifiers()) {
            table = table.toLowerCase();
            if (schema != null)
                schema = table.toLowerCase();
        } else if (metaData.storesUpperCaseIdentifiers()) {
            table = table.toUpperCase();
            if (schema != null)
                schema = schema.toUpperCase();
        }

        dbev.generatedKeys = metaData.supportsGetGeneratedKeys();
        ResultSet tables = metaData.getTables(null, schema, table, null);
        if (tables.next()) {
            dbev.table = tables.getString("TABLE_NAME");
            dbev.schema = tables.getString("TABLE_SCHEM");
        } else
            throw new ExternalVariableModuleException("Table \"" + table + "\" not found in database.");

        tables.close();

        List<Element> columns = DOMUtils.findChildrenByName(config, new QName(JDBC_NS, "column"));

        for (Element col : columns) {
            String name = col.getAttribute("name");
            String colname = col.getAttribute("column-name");
            String key = col.getAttribute("key");
            String gentype = col.getAttribute("generator");
            String expression = col.getAttribute("expression");

            if (key == null || "".equals(key))
                key = "no";
            if (gentype == null || "".equals(gentype))
                gentype = GenType.none.toString();
            if (colname == null || "".equals(colname))
                colname = name;

            if (name == null || "".equals(name))
                throw new ExternalVariableModuleException(
                        "External variable " + evarId + " <column> element must have \"name\" attribute. ");

            if (metaData.storesLowerCaseIdentifiers())
                colname = colname.toLowerCase();
            else if (metaData.storesUpperCaseIdentifiers())
                colname = colname.toUpperCase();

            GenType gtype;
            try {
                gtype = GenType.valueOf(gentype);
            } catch (Exception ex) {
                throw new ExternalVariableModuleException("External variable " + evarId + " column \"" + name
                        + "\" generator type \"" + gentype + "\" is unknown.");

            }

            if (gtype == GenType.expression && (expression == null || "".equals(expression)))
                throw new ExternalVariableModuleException("External variable " + evarId + " column \"" + name
                        + "\" used \"expression\" generator, but did not specify an expression");

            Column c = dbev.new Column(name, colname, key.equalsIgnoreCase("yes"), gtype, expression);
            ResultSet cmd = metaData.getColumns(null, dbev.schema, dbev.table, colname);
            try {
                if (cmd.next()) {
                    c.dataType = cmd.getInt("DATA_TYPE");
                    c.nullok = cmd.getInt("NULLABLE") != 0;
                } else
                    throw new ExternalVariableModuleException("External variable " + evarId + " referenced "
                            + "non-existant column \"" + colname + "\"!");
            } finally {
                cmd.close();
            }

            dbev.addColumn(c);
        }

        if (dbev.numColumns() == 0)
            throw new ExternalVariableModuleException(
                    "External variable " + evarId + " did not have any <column> elements!");

        _vars.put(evarId, dbev);
    } catch (SQLException se) {
        throw new ExternalVariableModuleException("SQL Error", se);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
        }
    }
}

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 ww w.java 2 s.  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.kawanfw.test.api.client.DatabaseMetaDataTest.java

public void test(Connection connection) throws Exception {
    MessageDisplayer.initClassDisplay(this.getClass().getSimpleName());

    DatabaseMetaData databaseMetaData = connection.getMetaData();

    // Test that getMetaData() will return value from cache
    databaseMetaData = connection.getMetaData();

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("Java Version : " + System.getProperty("java.version"));
        MessageDisplayer.display("AceQL Version: " + ((RemoteConnection) connection).getVersion());
        MessageDisplayer.display("AceQL Url    : " + ((RemoteConnection) connection).getUrl());
        MessageDisplayer.display("");
    }/*w  ww  . j a  v a 2  s  .  c  o m*/

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("((RemoteConnection)connection).clone();");
        Connection connection2 = ((RemoteConnection) connection).clone();
        @SuppressWarnings("unused")
        DatabaseMetaData databaseMetaData2 = connection2.getMetaData();
        connection2.close();
    }

    MessageDisplayer.display("General info (no Assert done):");

    MessageDisplayer.display("connection.getCatalog()                     : " + connection.getCatalog());

    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductName()   : " + databaseMetaData.getDatabaseProductName());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductVersion(): " + databaseMetaData.getDatabaseProductVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMajorVersion()  : " + databaseMetaData.getDatabaseMajorVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMinorVersion()  : " + databaseMetaData.getDatabaseMinorVersion());
    MessageDisplayer.display(
            "databaseMetaData.allProceduresAreCallable() : " + databaseMetaData.allProceduresAreCallable());
    // SystemOutHandle.display(DatabaseMetaData.bestRowSession);
    MessageDisplayer.display("");

    // SystemOutHandle.display(databaseMetaData.autoCommitFailureClosesAllResultSets());

    MessageDisplayer.display("databaseMetaData.getCatalogTerm(): " + databaseMetaData.getCatalogTerm());

    try {

        MessageDisplayer.display(
                "databaseMetaData.supportsStoredProcedures(): " + databaseMetaData.supportsStoredProcedures());

        MessageDisplayer.display("databaseMetaData.supportsStoredFunctionsUsingCallSyntax(): "
                + databaseMetaData.supportsStoredFunctionsUsingCallSyntax());

    } catch (Throwable e) {
        MessageDisplayer.display(e.toString());
    }

    MessageDisplayer.display("connection.getAutoCommit(): " + connection.getAutoCommit());

    MessageDisplayer.display("databaseMetaData.getDefaultTransactionIsolation()    : "
            + databaseMetaData.getDefaultTransactionIsolation());

    MessageDisplayer
            .display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_UNCOMMITTED): "
                    + databaseMetaData
                            .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_COMMITTED): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_REPEATABLE_READ): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));

    MessageDisplayer
            .display("databaseMetaData.supportsBatchUpdates()    : " + databaseMetaData.supportsBatchUpdates());
    MessageDisplayer
            .display("databaseMetaData.supportsSavepoints()      : " + databaseMetaData.supportsSavepoints());
    MessageDisplayer.display(
            "databaseMetaData.supportsGetGeneratedKeys(): " + databaseMetaData.supportsGetGeneratedKeys());

    if (!new SqlUtil(connection).isTeradata() && !new SqlUtil(connection).isInformix()) {
        Assert.assertEquals(true,
                databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));
    }

    Assert.assertEquals("databaseMetaData.supportsBatchUpdates()", true,
            databaseMetaData.supportsBatchUpdates());

    if (!new SqlUtil(connection).isSQLAnywhere() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals("databaseMetaData.supportsGetGeneratedKeys()", true,
                databaseMetaData.supportsGetGeneratedKeys());
    }
    // Informix does not support savepoints
    SqlUtil sqlUtil = new SqlUtil(connection);
    if (!sqlUtil.isInformix() && !sqlUtil.isTeradata() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals(true, databaseMetaData.supportsSavepoints());
    }

    MessageDisplayer.display("");

    String catalog = null;
    String schema = null;
    String table = "customer";

    // Table name must be uppercase for Oracle & DB2, lowercase for MySQL
    // and PostgreSQL
    if (new SqlUtil(connection).isOracle() || new SqlUtil(connection).isHSQLDB()
            || new SqlUtil(connection).isDB2()) {
        table = table.toUpperCase();
    }

    ResultSet rs = null;

    if (!new SqlUtil(connection).isAccess()) {

        rs = databaseMetaData.getPrimaryKeys(catalog, schema, table);

        printResultSet(rs);

        boolean rsNext = false;

        while (rs.next()) {
            rsNext = true;
            String keyColumnName = rs.getString("COLUMN_NAME");
            MessageDisplayer.display("Primary Key is: " + keyColumnName + " for Table: " + table);
            Assert.assertEquals("customer_id", keyColumnName.toLowerCase());
        }

        if (!new SqlUtil(connection).isH2()) {
            Assert.assertEquals(true, rsNext);
        }

        rs.close();
    }

    // boolean returnNow = true;
    // if (returnNow) return;

    String[] types = { "TABLE", "VIEW" };
    rs = databaseMetaData.getTables(null, null, null, types);

    Set<String> tablesSet = new HashSet<String>();

    Set<String> ourTables = new HashSet<String>();
    ourTables.add("banned_usernames");
    ourTables.add("customer");
    ourTables.add("customer_auto");
    ourTables.add("orderlog");
    ourTables.add("user_login");

    MessageDisplayer.display("");
    while (rs.next()) {
        table = rs.getString("TABLE_NAME");

        if (ourTables.contains(table.toLowerCase())) {
            MessageDisplayer.display("Table: " + table);
        }

        tablesSet.add(table.toLowerCase());
    }

    // printResultSet(rs);

    testTable("banned_usernames", tablesSet);
    testTable("customer", tablesSet);
    testTable("orderlog", tablesSet);
    testTable("user_login", tablesSet);

    rs.close();
}

From source file:org.rimudb.Database.java

/**
 * Get this database's meta data//from   www  . j  av  a2  s.  c om
 */
private RimuDBDatabaseMetaData lookupDatabaseInfo() throws RimuDBException {
    RimuDBDatabaseMetaData metaData = new RimuDBDatabaseMetaData();
    Connection con = null;
    DatabaseMetaData dbmd = null;
    ResultSet rs = null;

    try {
        con = getDatabaseConnection();
        dbmd = con.getMetaData();

        metaData.setDatabaseProductName(dbmd.getDatabaseProductName());
        metaData.setDatabaseMajorVersion(dbmd.getDatabaseMajorVersion());
        metaData.setSupportsGetGeneratedKeys(dbmd.supportsGetGeneratedKeys());

    } catch (SQLException e) {
        throw new RimuDBException(e);

    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
            }
        }
    }

    return metaData;
}

From source file:org.springframework.jdbc.core.metadata.GenericTableMetaDataProvider.java

@Override
public void initializeWithMetaData(DatabaseMetaData databaseMetaData) throws SQLException {
    try {/* ww w.j av  a 2s  .  com*/
        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());
        }
    }
}