Example usage for java.sql SQLException getSQLState

List of usage examples for java.sql SQLException getSQLState

Introduction

In this page you can find the example usage for java.sql SQLException getSQLState.

Prototype

public String getSQLState() 

Source Link

Document

Retrieves the SQLState for this SQLException object.

Usage

From source file:mom.trd.opentheso.bdd.helper.RelationsHelper.java

/**
 * Cette fonction permet de rajouter une relation terme gnrique  un
 * concept/*from   w w w. j a v a2s . c  o m*/
 *
 * @param conn
 * @param idConceptNT
 * @param idThesaurus
 * @param idConceptBT
 * @param idUser
 * @return boolean
 */
public boolean addRelationBT(Connection conn, String idConceptNT, String idThesaurus, String idConceptBT,
        int idUser) {

    Statement stmt;
    boolean status = false;

    try {
        try {
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            try {
                if (!new RelationsHelper().addRelationHistorique(conn, idConceptNT, idThesaurus, idConceptBT,
                        "BT", idUser, "ADD")) {
                    conn.rollback();
                    conn.close();
                    return false;
                }
                if (!new RelationsHelper().addRelationHistorique(conn, idConceptBT, idThesaurus, idConceptNT,
                        "NT", idUser, "ADD")) {
                    conn.rollback();
                    conn.close();
                    return false;
                }

                String query = "Insert into hierarchical_relationship"
                        + "(id_concept1, id_thesaurus, role, id_concept2)" + " values (" + "'" + idConceptNT
                        + "'" + ",'" + idThesaurus + "'" + ",'BT'" + ",'" + idConceptBT + "')";

                stmt.executeUpdate(query);
                query = "Insert into hierarchical_relationship"
                        + "(id_concept1, id_thesaurus, role, id_concept2)" + " values (" + "'" + idConceptBT
                        + "'" + ",'" + idThesaurus + "'" + ",'NT'" + ",'" + idConceptNT + "')";
                stmt.executeUpdate(query);
                status = true;
                // conn.commit();
            } finally {
                stmt.close();
            }
        } finally {
            //         conn.close();
        }
    } catch (SQLException sqle) {
        // Log exception
        //  if (sqle.getMessage().contains("duplicate key value violates unique constraint")) {

        if (!sqle.getSQLState().equalsIgnoreCase("23505")) {
            log.error("Error while adding relation BT of Concept : " + idConceptNT, sqle);
        }
    }
    return status;
}

From source file:org.apache.hadoop.hive.metastore.txn.TestTxnHandler.java

@Test
@Ignore//from   w  w w . ja  v a 2  s.  co  m
public void deadlockDetected() throws Exception {
    LOG.debug("Starting deadlock test");
    Connection conn = txnHandler.getDbConn(Connection.TRANSACTION_SERIALIZABLE);
    Statement stmt = conn.createStatement();
    long now = txnHandler.getDbTime(conn);
    stmt.executeUpdate("insert into TXNS (txn_id, txn_state, txn_started, txn_last_heartbeat, "
            + "txn_user, txn_host) values (1, 'o', " + now + ", " + now + ", 'shagy', " + "'scooby.com')");
    stmt.executeUpdate("insert into HIVE_LOCKS (hl_lock_ext_id, hl_lock_int_id, hl_txnid, "
            + "hl_db, hl_table, hl_partition, hl_lock_state, hl_lock_type, hl_last_heartbeat, "
            + "hl_user, hl_host) values (1, 1, 1, 'mydb', 'mytable', 'mypartition', '" + txnHandler.LOCK_WAITING
            + "', '" + txnHandler.LOCK_EXCLUSIVE + "', " + now + ", 'fred', " + "'scooby.com')");
    conn.commit();
    txnHandler.closeDbConn(conn);

    final AtomicBoolean sawDeadlock = new AtomicBoolean();

    final Connection conn1 = txnHandler.getDbConn(Connection.TRANSACTION_SERIALIZABLE);
    final Connection conn2 = txnHandler.getDbConn(Connection.TRANSACTION_SERIALIZABLE);
    try {

        for (int i = 0; i < 5; i++) {
            Thread t1 = new Thread() {
                @Override
                public void run() {
                    try {
                        try {
                            updateTxns(conn1);
                            updateLocks(conn1);
                            Thread.sleep(1000);
                            conn1.commit();
                            LOG.debug("no exception, no deadlock");
                        } catch (SQLException e) {
                            try {
                                txnHandler.checkRetryable(conn1, e, "thread t1");
                                LOG.debug("Got an exception, but not a deadlock, SQLState is " + e.getSQLState()
                                        + " class of exception is " + e.getClass().getName() + " msg is <"
                                        + e.getMessage() + ">");
                            } catch (TxnHandler.RetryException de) {
                                LOG.debug("Forced a deadlock, SQLState is " + e.getSQLState() + " class of "
                                        + "exception is " + e.getClass().getName() + " msg is <"
                                        + e.getMessage() + ">");
                                sawDeadlock.set(true);
                            }
                        }
                        conn1.rollback();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            };

            Thread t2 = new Thread() {
                @Override
                public void run() {
                    try {
                        try {
                            updateLocks(conn2);
                            updateTxns(conn2);
                            Thread.sleep(1000);
                            conn2.commit();
                            LOG.debug("no exception, no deadlock");
                        } catch (SQLException e) {
                            try {
                                txnHandler.checkRetryable(conn2, e, "thread t2");
                                LOG.debug("Got an exception, but not a deadlock, SQLState is " + e.getSQLState()
                                        + " class of exception is " + e.getClass().getName() + " msg is <"
                                        + e.getMessage() + ">");
                            } catch (TxnHandler.RetryException de) {
                                LOG.debug("Forced a deadlock, SQLState is " + e.getSQLState() + " class of "
                                        + "exception is " + e.getClass().getName() + " msg is <"
                                        + e.getMessage() + ">");
                                sawDeadlock.set(true);
                            }
                        }
                        conn2.rollback();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            };

            t1.start();
            t2.start();
            t1.join();
            t2.join();
            if (sawDeadlock.get())
                break;
        }
        assertTrue(sawDeadlock.get());
    } finally {
        conn1.rollback();
        txnHandler.closeDbConn(conn1);
        conn2.rollback();
        txnHandler.closeDbConn(conn2);
    }
}

From source file:org.exist.xquery.modules.sql.ExecuteFunction.java

/**
 * evaluate the call to the XQuery execute() function, it is really the main entry point of this class.
 *
 * @param   args             arguments from the execute() function call
 * @param   contextSequence  the Context Sequence to operate on (not used here internally!)
 *
 * @return  A node representing the SQL result set
 *
 * @throws  XPathException  DOCUMENT ME!
 *
 * @see     org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
 *//*w  ww. j a va  2  s.c om*/
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // was a connection and SQL statement specified?
    if (args[0].isEmpty() || args[1].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    // get the Connection
    long connectionUID = ((IntegerValue) args[0].itemAt(0)).getLong();
    Connection con = SQLModule.retrieveConnection(context, connectionUID);

    if (con == null) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    boolean preparedStmt = false;

    //setup the SQL statement
    String sql = null;
    Statement stmt = null;
    boolean executeResult = false;
    ResultSet rs = null;

    try {
        boolean makeNodeFromColumnName = false;
        MemTreeBuilder builder = context.getDocumentBuilder();
        int iRow = 0;

        //SQL or PreparedStatement?
        if (args.length == 3) {

            // get the SQL statement
            sql = args[1].getStringValue();
            stmt = con.createStatement();
            makeNodeFromColumnName = ((BooleanValue) args[2].itemAt(0)).effectiveBooleanValue();

            //execute the statement
            executeResult = stmt.execute(sql);

        } else if (args.length == 4) {

            preparedStmt = true;

            //get the prepared statement
            long statementUID = ((IntegerValue) args[1].itemAt(0)).getLong();
            PreparedStatementWithSQL stmtWithSQL = SQLModule.retrievePreparedStatement(context, statementUID);
            sql = stmtWithSQL.getSql();
            stmt = stmtWithSQL.getStmt();
            makeNodeFromColumnName = ((BooleanValue) args[3].itemAt(0)).effectiveBooleanValue();

            if (!args[2].isEmpty()) {
                setParametersOnPreparedStatement(stmt, (Element) args[2].itemAt(0));
            }

            //execute the prepared statement
            executeResult = ((PreparedStatement) stmt).execute();
        } else {
            //TODO throw exception
        }

        // DW: stmt can be null ?

        // execute the query statement
        if (executeResult) {
            /* SQL Query returned results */

            // iterate through the result set building an XML document
            rs = stmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            int iColumns = rsmd.getColumnCount();

            builder.startDocument();

            builder.startElement(new QName("result", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
            builder.addAttribute(new QName("count", null, null), String.valueOf(-1));

            while (rs.next()) {
                builder.startElement(new QName("row", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
                builder.addAttribute(new QName("index", null, null), String.valueOf(rs.getRow()));

                // get each tuple in the row
                for (int i = 0; i < iColumns; i++) {
                    String columnName = rsmd.getColumnLabel(i + 1);

                    if (columnName != null) {

                        String colElement = "field";

                        if (makeNodeFromColumnName && columnName.length() > 0) {
                            // use column names as the XML node

                            /**
                             * Spaces in column names are replaced with
                             * underscore's
                             */
                            colElement = SQLUtils.escapeXmlAttr(columnName.replace(' ', '_'));
                        }

                        builder.startElement(new QName(colElement, SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                null);

                        if (!makeNodeFromColumnName || columnName.length() <= 0) {
                            String name;

                            if (columnName.length() > 0) {
                                name = SQLUtils.escapeXmlAttr(columnName);
                            } else {
                                name = "Column: " + String.valueOf(i + 1);
                            }

                            builder.addAttribute(new QName("name", null, null), name);
                        }

                        builder.addAttribute(
                                new QName(TYPE_ATTRIBUTE_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                rsmd.getColumnTypeName(i + 1));
                        builder.addAttribute(new QName(TYPE_ATTRIBUTE_NAME, Namespaces.SCHEMA_NS, "xs"),
                                Type.getTypeName(SQLUtils.sqlTypeToXMLType(rsmd.getColumnType(i + 1))));

                        //get the content
                        if (rsmd.getColumnType(i + 1) == Types.SQLXML) {
                            //parse sqlxml value
                            try {
                                final SQLXML sqlXml = rs.getSQLXML(i + 1);

                                if (rs.wasNull()) {
                                    // Add a null indicator attribute if the value was SQL Null
                                    builder.addAttribute(
                                            new QName("null", SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                            "true");
                                } else {

                                    SAXParserFactory factory = SAXParserFactory.newInstance();
                                    factory.setNamespaceAware(true);
                                    InputSource src = new InputSource(sqlXml.getCharacterStream());
                                    SAXParser parser = factory.newSAXParser();
                                    XMLReader xr = parser.getXMLReader();

                                    SAXAdapter adapter = new AppendingSAXAdapter(builder);
                                    xr.setContentHandler(adapter);
                                    xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
                                    xr.parse(src);
                                }
                            } catch (Exception e) {
                                throw new XPathException(
                                        "Could not parse column of type SQLXML: " + e.getMessage(), e);
                            }
                        } else {
                            //otherwise assume string value
                            final String colValue = rs.getString(i + 1);

                            if (rs.wasNull()) {
                                // Add a null indicator attribute if the value was SQL Null
                                builder.addAttribute(
                                        new QName("null", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), "true");
                            } else {
                                if (colValue != null) {
                                    builder.characters(SQLUtils.escapeXmlText(colValue));
                                }
                            }
                        }

                        builder.endElement();
                    }
                }

                builder.endElement();
                iRow++;
            }

            builder.endElement();
        } else {
            /* SQL Query performed updates */

            builder.startDocument();

            builder.startElement(new QName("result", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
            builder.addAttribute(new QName("updateCount", null, null), String.valueOf(stmt.getUpdateCount()));
            builder.endElement();
        }

        // Change the root element count attribute to have the correct value
        NodeValue node = (NodeValue) builder.getDocument().getDocumentElement();
        Node count = node.getNode().getAttributes().getNamedItem("count");

        if (count != null) {
            count.setNodeValue(String.valueOf(iRow));
        }

        builder.endDocument();

        // return the XML result set
        return (node);

    } catch (SQLException sqle) {
        LOG.error("sql:execute() Caught SQLException \"" + sqle.getMessage() + "\" for SQL: \"" + sql + "\"",
                sqle);

        //return details about the SQLException
        MemTreeBuilder builder = context.getDocumentBuilder();

        builder.startDocument();
        builder.startElement(new QName("exception", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

        boolean recoverable = false;

        if (sqle instanceof SQLRecoverableException) {
            recoverable = true;
        }
        builder.addAttribute(new QName("recoverable", null, null), String.valueOf(recoverable));

        builder.startElement(new QName("state", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.characters(sqle.getSQLState());
        builder.endElement();

        builder.startElement(new QName("message", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

        String state = sqle.getMessage();

        if (state != null) {
            builder.characters(state);
        }

        builder.endElement();

        builder.startElement(new QName("stack-trace", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        ByteArrayOutputStream bufStackTrace = new ByteArrayOutputStream();
        sqle.printStackTrace(new PrintStream(bufStackTrace));
        builder.characters(new String(bufStackTrace.toByteArray()));
        builder.endElement();

        builder.startElement(new QName("sql", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.characters(SQLUtils.escapeXmlText(sql));
        builder.endElement();

        if (stmt instanceof PreparedStatement) {
            Element parametersElement = (Element) args[2].itemAt(0);

            if (parametersElement.getNamespaceURI().equals(SQLModule.NAMESPACE_URI)
                    && parametersElement.getLocalName().equals(PARAMETERS_ELEMENT_NAME)) {
                NodeList paramElements = parametersElement.getElementsByTagNameNS(SQLModule.NAMESPACE_URI,
                        PARAM_ELEMENT_NAME);

                builder.startElement(
                        new QName(PARAMETERS_ELEMENT_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

                for (int i = 0; i < paramElements.getLength(); i++) {
                    Element param = ((Element) paramElements.item(i));
                    String value = param.getFirstChild().getNodeValue();
                    String type = param.getAttributeNS(SQLModule.NAMESPACE_URI, TYPE_ATTRIBUTE_NAME);

                    builder.startElement(
                            new QName(PARAM_ELEMENT_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

                    builder.addAttribute(
                            new QName(TYPE_ATTRIBUTE_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), type);
                    builder.characters(SQLUtils.escapeXmlText(value));

                    builder.endElement();
                }

                builder.endElement();
            }
        }

        builder.startElement(new QName("xquery", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.addAttribute(new QName("line", null, null), String.valueOf(getLine()));
        builder.addAttribute(new QName("column", null, null), String.valueOf(getColumn()));
        builder.endElement();

        builder.endElement();
        builder.endDocument();

        return ((NodeValue) builder.getDocument().getDocumentElement());
    } finally {

        // close any record set or statement
        if (rs != null) {

            try {
                rs.close();
            } catch (SQLException se) {
                LOG.warn("Unable to cleanup JDBC results", se);
            }
            rs = null;
        }

        if (!preparedStmt && stmt != null) {

            try {
                stmt.close();
            } catch (SQLException se) {
                LOG.warn("Unable to cleanup JDBC results", se);
            }
            stmt = null;
        }

    }
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBWriter.java

/** Commit the current database transaction */
public void commit(Connection conn) throws TransactionInterruptedException {
    try {/*from  www . ja  v  a 2 s  . c o m*/
        dbc.commit(conn);
    } catch (SQLException e) {
        if (e.getSQLState().equals("40001")) {
            log.warn("Database deadlock detected -- alerting TradeServ");
            TransactionInterruptedException te = new TransactionInterruptedException();
            te.setDeadlock(true);
            throw te;
        } else {
            log.error("Failed to commit the last transaction to the database", e);
            throw new TransactionInterruptedException();
        }
    }
}

From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java

public boolean isUniqueKeyViolation(Throwable ex) {
    boolean primaryKeyViolation = false;
    if (primaryKeyViolationCodes != null || primaryKeyViolationSqlStates != null) {
        SQLException sqlEx = findSQLException(ex);
        if (sqlEx != null) {
            if (primaryKeyViolationCodes != null) {
                int errorCode = sqlEx.getErrorCode();
                for (int primaryKeyViolationCode : primaryKeyViolationCodes) {
                    if (primaryKeyViolationCode == errorCode) {
                        primaryKeyViolation = true;
                        break;
                    }//w ww. j a  v  a  2  s  .  c  o  m
                }
            }

            if (primaryKeyViolationSqlStates != null) {
                String sqlState = sqlEx.getSQLState();
                if (sqlState != null) {
                    for (String primaryKeyViolationSqlState : primaryKeyViolationSqlStates) {
                        if (primaryKeyViolationSqlState != null
                                && primaryKeyViolationSqlState.equals(sqlState)) {
                            primaryKeyViolation = true;
                            break;
                        }
                    }
                }
            }

            if (primaryKeyViolationMessageParts != null) {
                String sqlMessage = sqlEx.getMessage();
                if (sqlMessage != null) {
                    sqlMessage = sqlMessage.toLowerCase();
                    for (String primaryKeyViolationMessagePart : primaryKeyViolationMessageParts) {
                        if (primaryKeyViolationMessagePart != null
                                && sqlMessage.contains(primaryKeyViolationMessagePart.toLowerCase())) {
                            primaryKeyViolation = true;
                            break;
                        }
                    }
                }
            }
        }
    }

    return primaryKeyViolation;
}

From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java

public boolean isForeignKeyViolation(Throwable ex) {
    boolean foreignKeyViolation = false;
    if (foreignKeyViolationCodes != null || foreignKeyViolationSqlStates != null) {
        SQLException sqlEx = findSQLException(ex);
        if (sqlEx != null) {
            if (foreignKeyViolationCodes != null) {
                int errorCode = sqlEx.getErrorCode();
                for (int foreignKeyViolationCode : foreignKeyViolationCodes) {
                    if (foreignKeyViolationCode == errorCode) {
                        foreignKeyViolation = true;
                        break;
                    }//from   w w  w . j a  va 2 s. c  o m
                }
            }

            if (foreignKeyViolationSqlStates != null) {
                String sqlState = sqlEx.getSQLState();
                if (sqlState != null) {
                    for (String foreignKeyViolationSqlState : foreignKeyViolationSqlStates) {
                        if (foreignKeyViolationSqlState != null
                                && foreignKeyViolationSqlState.equals(sqlState)) {
                            foreignKeyViolation = true;
                            break;
                        }
                    }
                }
            }

            if (foreignKeyViolationMessageParts != null) {
                String sqlMessage = sqlEx.getMessage();
                if (sqlMessage != null) {
                    sqlMessage = sqlMessage.toLowerCase();
                    for (String foreignKeyViolationMessagePart : foreignKeyViolationMessageParts) {
                        if (foreignKeyViolationMessagePart != null
                                && sqlMessage.contains(foreignKeyViolationMessagePart.toLowerCase())) {
                            foreignKeyViolation = true;
                            break;
                        }
                    }
                }
            }
        }
    }

    return foreignKeyViolation;
}

From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java

/**
 * Tests an import scenario where a quoted column is missing the end quote and the EOF is
 * reached before the maximum number of lines in a quoted column is exceeded.
 *
 * @throws Exception//from   w ww  .  j  a v a2 s  .  c o m
 */
@Test
public void testMissingEndQuoteForQuotedColumnEOF() throws Exception {
    String badDirPath = BADDIR.getCanonicalPath();
    String csvPath = getResourceDirectory() + "import/missing-end-quote/employees.csv";
    try {
        testMissingEndQuoteForQuotedColumn(spliceSchemaWatcher.schemaName, TABLE_18, csvPath, "NAME,TITLE,AGE",
                badDirPath, 0, 1, "false");
        fail("Expected to many bad records.");
    } catch (SQLException e) {
        assertEquals("Expected too many bad records but got: " + e.getLocalizedMessage(), "SE009",
                e.getSQLState());
        SpliceUnitTest.assertBadFileContainsError(new File(badDirPath), "employees.csv", null,
                "unexpected end of file while reading quoted column beginning on line 2 and ending on line 6");
    }
}

From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java

/**
 * Tests an import scenario where a quoted column is missing the end quote and the
 * maximum number of lines in a quoted column is exceeded.
 *
 * @throws Exception/*  ww  w  . j a  v  a2 s  .com*/
 */
@Test
public void testMissingEndQuoteForQuotedColumnMax() throws Exception {
    String badDirPath = BADDIR.getCanonicalPath();
    String csvPath = getResourceDirectory() + "import/missing-end-quote/employeesMaxQuotedColumnLines.csv";
    try {
        testMissingEndQuoteForQuotedColumn(spliceSchemaWatcher.schemaName, TABLE_18, csvPath, "NAME,TITLE,AGE",
                badDirPath, 0, 199999, "false");
        fail("Expected to many bad records.");
    } catch (SQLException e) {
        assertEquals("Expected too many bad records but got: " + e.getLocalizedMessage(), "SE009",
                e.getSQLState());
        SpliceUnitTest.assertBadFileContainsError(new File(badDirPath), "employeesMaxQuotedColumnLines.csv",
                null, "Quoted column beginning on line 3 has exceed the maximum allowed lines");
    }
}

From source file:org.rimudb.Table.java

/**
 * Add a record to the table.//  w  w  w .j  a  va2  s . co m
 * 
 * @param record Record
 */
public void add(Record record) throws RimuDBException {
    Connection con = null;
    int statID = 0;
    PreparedStatement stmt = null;

    try {
        con = getDatabase().getDatabaseConnection();

        String sql = sqlStatementCache.getInsertSQL();
        if (sql == null) {
            sql = sqlAdapter.getInsertStatement(tableMetaData, getTableName());
            sqlStatementCache.setInsertSQL(sql);
        }

        // Get the statistic ID
        int loggingType = getDatabase().getDatabaseConfiguration().getLoggingType();
        if (loggingType == DatabaseConfiguration.LOG_STATISTICS) {
            statID = StatisticCollector.getInstance().createStatistic(sql);
        } else if (loggingType == DatabaseConfiguration.LOG_SQL_ONLY) {
            log.info("SQL=" + sql);
        }

        stmt = createPreparedStatement(con, sql, CrudType.CREATE);

        recordBinder.bindStatementForInsert(stmt, record);

        if (statID > 0)
            StatisticCollector.getInstance().logEvent(statID, "preparetime");

        stmt.executeUpdate();

        if (statID > 0)
            StatisticCollector.getInstance().logEvent(statID, "executetime");

        // Mark the record as in existence
        record.setExists(true);

        // If we had auto-increment keys then update the record with their new values
        if (tableMetaData.hasAutoIncrementKeys()) {
            if (sqlAdapter.getDatabaseMetaData().getSupportsGetGeneratedKeys()) {
                populateGeneratedKeys(stmt, record);

                // If the generated key can be derived from the insert statement.
            } else if (sqlAdapter.isInsertIndentityStatementSupported()) {

                // TODO: Handle this somehow

                // If a separate statement needs to be executed.
            } else {
                ColumnMetaData columnMetaData = getTableMetaData().getAutoIncrementColumn();
                String autoIncrementColumn = columnMetaData.getColumnName();
                int columnType = columnMetaData.getColumnType();
                String identitySelectSQL = sqlAdapter.getIdentitySelectSQL(getTableName(), autoIncrementColumn,
                        columnType);

                // Execute the statement to get the identity value
                try {
                    //fetch the generated id in a separate query
                    PreparedStatement ps = con.prepareStatement(identitySelectSQL);
                    try {
                        populateQueriedKeys(ps, record);
                    } finally {
                        ps.close();
                    }

                } catch (SQLException sqle) {
                    throw new RimuDBException(sqle,
                            "Could not retrieve generated id after insert for sql: " + sql);
                }

            }
        }

        if (statID > 0) {
            StatisticCollector.getInstance().logEvent(statID, "processtime");
            if (StatisticCollector.getInstance().exceedsThreshold(statID,
                    getDatabase().getDatabaseConfiguration().getLoggingThreshold())) {
                String text = StatisticCollector.getInstance().formatStatistics(statID,
                        getDatabase().getStatisticFormatter());
                log.info(text);
            }
            StatisticCollector.getInstance().removeID(statID);
        }

    } catch (SQLException e) {
        if (e.getSQLState() != null && e.getSQLState().startsWith("23")) {
            throw new ConstraintViolationException(e);
        } else {
            throw new RimuDBException(e);
        }

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

From source file:com.splicemachine.derby.impl.load.HdfsImportIT.java

@Test
public void testFailedImportNullBadDir() throws Exception {
    // DB-5017: When bad record dir is null or empty, the input file dir becomes the bad record dir
    String inputFileName = "constraintViolation.csv";
    String inputFileOrigin = getResourceDirectory() + inputFileName;
    // copy the given input file under a temp folder so that it will get cleaned up
    // this used to go under the "target/test-classes" folder but doesn't work when we execute test from
    // a different location.
    File newImportFile = tempFolder.newFile(inputFileName);
    FileUtils.copyFile(new File(inputFileOrigin), newImportFile);
    assertTrue("Import file copy failed: " + newImportFile.getCanonicalPath(), newImportFile.exists());
    String badFileName = newImportFile.getParent() + "/" + inputFileName + ".bad";

    PreparedStatement ps = methodWatcher.prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA(" + "'%s'," + // schema name
            "'%s'," + // table name
            "null," + // insert column list
            "'%s'," + // file path
            "','," + // column delimiter
            "null," + // character delimiter
            "null," + // timestamp format
            "null," + // date format
            "null," + // time format
            "%d," + // max bad records
            "null," + // bad record dir
            "null," + // has one line records
            "null)", // char set
            spliceSchemaWatcher.schemaName, TABLE_20, newImportFile.getCanonicalPath(), 0));
    try {/*from  ww  w  .  j av a  2 s .com*/
        ps.execute();
        fail("Too many bad records.");
    } catch (SQLException e) {
        assertEquals("Expected too many bad records, but got: " + e.getLocalizedMessage(), "SE009",
                e.getSQLState());
    }
    boolean exists = existsBadFile(new File(newImportFile.getParent()), inputFileName + ".bad");
    assertTrue("Bad file " + badFileName + " does not exist.", exists);
}