Example usage for java.sql SQLException getErrorCode

List of usage examples for java.sql SQLException getErrorCode

Introduction

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

Prototype

public int getErrorCode() 

Source Link

Document

Retrieves the vendor-specific exception code for this SQLException object.

Usage

From source file:io.confluent.connect.jdbc.EmbeddedDerby.java

public void close() throws SQLException {
    conn.close();/* ww  w.  j  a v  a  2  s  .  c om*/

    // Derby requires more than just closing the connection to clear out the embedded data
    try {
        DriverManager.getConnection(getShutdownUrl());
    } catch (SQLException se) {
        // Clean shutdown always throws this exception
        if (((se.getErrorCode() == 45000) && ("08006".equals(se.getSQLState())))) {
            // Note that for single database shutdown, the expected
            // SQL state is "08006", and the error code is 45000.
        } else {
            throw se;
        }
    }
}

From source file:IDlook.java

public void connectToDB() {
    try {// w w  w  .ja v  a 2  s .com
        connection = DriverManager
                .getConnection("jdbc:mysql://192.168.1.25/identification?user=spider&password=spider");
        statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

    } catch (SQLException connectException) {
        System.out.println(connectException.getMessage());
        System.out.println(connectException.getSQLState());
        System.out.println(connectException.getErrorCode());
        System.exit(1);
    }
}

From source file:com.yahoo.dba.perf.myperf.springmvc.QueryController.java

@Override
protected ModelAndView handleRequestImpl(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    int status = Constants.STATUS_OK;
    String message = "OK";

    logger.info("receive url " + req.getQueryString());
    QueryParameters qps = null;//from www .  j  av a2s .co m
    DBInstanceInfo dbinfo = null;
    ModelAndView mv = null;
    ResultList rList = null;
    LinkedHashMap<String, ResultList> listMap = null; //if multiple result set

    qps = WebAppUtil.parseRequestParameter(req);
    //validation input
    String validation = qps.validate();
    if (validation == null || validation.isEmpty()) {
        //do we have such query?
        try {
            QueryInputValidator.validateSql(this.frameworkContext.getSqlManager(), qps);
        } catch (Exception ex) {
            validation = ex.getMessage();
        }
    }
    if (validation != null && !validation.isEmpty())
        return this.respondFailure("Input validation: " + validation, req);

    //valid DB?
    dbinfo = this.frameworkContext.getDbInfoManager().findDB(qps.getGroup(), qps.getHost());
    if (dbinfo == null)
        return this.respondFailure("Cannot find database (" + qps.getGroup() + ", " + qps.getHost() + ")", req);

    //create connection if needed
    DBConnectionWrapper connWrapper = null;
    Sql sql = this.frameworkContext.getSqlManager().getSql(qps.getSql());
    if (sql == null || sql.getQueryProcessor() == null
            || !CUSTOMER_PROCESSOR.containsKey(sql.getQueryProcessor())
            || CUSTOMER_PROCESSOR.get(sql.getQueryProcessor()).requireDBConnection()) {
        //connect to db
        try {
            connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo);

            if (connWrapper == null)
                return this.respondFailure("Failed to connecto to database (" + dbinfo + ")", req);
        } catch (Throwable th) {
            logger.log(Level.SEVERE, "Exception", th);
            status = Constants.STATUS_BAD;
            return this.respondFailure("Failed to connecto to database (" + dbinfo + "): " + th.getMessage(),
                    req);
        }
    }

    //when we reach here, at least we have valid query and can connect to db if needed   
    WebAppUtil.storeLastDbInfoRequest(qps.getGroup(), qps.getHost(), req);

    try {
        logger.info("execute query " + qps.getSql());
        if (sql != null && sql.getQueryProcessor() != null
                && CUSTOMER_PROCESSOR.containsKey(sql.getQueryProcessor())) //custom processor
        {
            CustomQueryProcessor prc = CUSTOMER_PROCESSOR.get(sql.getQueryProcessor());
            if (prc.isMultiple()) {
                listMap = new LinkedHashMap<String, ResultList>();
                prc.queryMultiple(frameworkContext, dbinfo, findUserFromRequest(req), connWrapper, qps,
                        listMap);
            } else
                rList = prc.querySingle(this.frameworkContext, dbinfo, findUserFromRequest(req), connWrapper,
                        qps);
        } else
            rList = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper,
                    qps.getMaxRows());
        logger.info("Done query " + qps.getSql() + " with " + (rList != null ? rList.getRows().size() : 0)
                + " records.");
        if (connWrapper != null)
            WebAppUtil.closeDBConnection(req, connWrapper, false);
    } catch (Throwable ex) {
        logger.log(Level.SEVERE, "Exception", ex);
        if (connWrapper != null) {
            if (ex instanceof SQLException) {
                SQLException sqlEx = SQLException.class.cast(ex);
                String msg = ex.getMessage();
                logger.info(sqlEx.getSQLState() + ", " + sqlEx.getErrorCode() + ", " + msg);
                //check if the connection is still good
                if (!DBUtils.checkConnection(connWrapper.getConnection())) {
                    WebAppUtil.closeDBConnection(req, connWrapper, true);
                } else
                    WebAppUtil.closeDBConnection(req, connWrapper, true);
            } else {
                WebAppUtil.closeDBConnection(req, connWrapper, false);
            }
        }
        status = Constants.STATUS_BAD;
        message = "Exception: " + ex.getMessage();
    }

    if (status != Constants.STATUS_OK)
        return this.respondFailure(message, req);

    if (rList != null && POST_PROCESSOR.containsKey(qps.getSql()))
        rList = POST_PROCESSOR.get(qps.getSql()).process(rList);

    mv = new ModelAndView(this.jsonView);
    if (listMap != null)
        mv.addObject("json_result", ResultListUtil.toMultiListJSONStringUpper(listMap, qps, status, message));
    else
        mv.addObject("json_result",
                ResultListUtil.toJSONString(filterResultList(rList, req), qps, status, message));
    return mv;
}

From source file:com.ipcglobal.fredimportcdh.TsvsToImpala.java

/**
 * Process tables./*from w w  w .ja  v  a2  s . c  o  m*/
 *
 * @throws Exception the exception
 */
private void processTables() throws Exception {
    String jdbcImpalaDriverClass = this.properties.getProperty("jdbcImpalaDriverClass").trim();
    String jdbcImpalaUrl = this.properties.getProperty("jdbcImpalaUrl").trim();
    String jdbcImpalaLogin = this.properties.getProperty("jdbcImpalaLogin").trim();
    String jdbcImpalaPassword = this.properties.getProperty("jdbcImpalaPassword").trim();

    String databaseNameFred = this.properties.getProperty("databaseNameFred").trim();
    String tableNameFred = properties.getProperty("tableNameFred");
    String stageTableSuffix = "_staging";
    Connection con = null;
    Statement statement = null;

    String databaseTableName = databaseNameFred + "." + tableNameFred;
    String databaseStageTableName = databaseNameFred + "." + tableNameFred + stageTableSuffix;

    try {

        Class.forName(jdbcImpalaDriverClass);
        con = DriverManager.getConnection(jdbcImpalaUrl, jdbcImpalaLogin, jdbcImpalaPassword);
        statement = con.createStatement();

        log.info("\tDrop/create internal and external staging table");
        statement.executeUpdate("DROP TABLE IF EXISTS " + databaseTableName);
        statement.executeUpdate("DROP TABLE IF EXISTS " + databaseStageTableName);

        log.info("\tCreate external staging table against the tsv's in HDFS");
        statement.executeUpdate(createStageTableStatement(databaseStageTableName));
        statement.executeUpdate("REFRESH " + databaseStageTableName);

        log.info("\tCreate internal table as select from external staging table");
        String sqlCreateAs = "create table " + databaseTableName + " stored as parquet as select * from "
                + databaseStageTableName;
        statement.executeUpdate(sqlCreateAs);
        statement.executeUpdate("REFRESH " + databaseTableName);

        log.info("\tDrop the staging table");
        statement.executeUpdate("DROP TABLE IF EXISTS " + databaseStageTableName);

        log.info("\tStart - COMPUTE STATS on internal table");
        String sqlComputeStats = "COMPUTE STATS " + databaseTableName;
        try {
            long before = System.currentTimeMillis();
            log.info(sqlComputeStats);
            statement.executeUpdate(sqlComputeStats);
            log.info("\tCOMPUTE STATS Insert Ok, Elapsed="
                    + convertMSecsToHMmSs(System.currentTimeMillis() - before));

        } catch (Exception e) {
            log.error("COMPUTE STATS, statement=" + sqlComputeStats, e);
            throw e;
        }

    } catch (SQLException se) {
        log.error(se);
        log.error("Cause: " + se.getCause());
        log.error("getErrorCode: " + se.getErrorCode());
        log.error("getSQLState: " + se.getSQLState());
        se.printStackTrace();
        throw se;
    } catch (Exception e) {
        log.error(e);
        e.printStackTrace();
        throw e;
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (Exception e) {
        }
        try {
            if (con != null)
                con.close();
        } catch (Exception e) {
        }
    }
}

From source file:de.ufinke.cubaja.sql.Database.java

/**
 * Executes SQL provided as <tt>Sql</tt> instance immediately.
 * <p>/* w ww  .jav a  2s  .  c om*/
 * There may be more than one SQL statement; each
 * statement separated by semicolon.
 * <p>
 * You may optionally specify any number of SQL codes which are expected
 * and should not throw an <tt>SQLException</tt>. This is
 * useful e.g. for <tt>drop</tt> statements.
 * The SQL codes are vendor specific. 
 * @param sql
 * @param acceptedSqlCodes
 * @throws SQLException
 */
public void execute(Sql sql, int... acceptedSqlCodes) throws SQLException {

    if (sql.hasVariables()) {
        throw new SQLException(text.get("execVariables"));
    }

    Statement statement = connection.createStatement();

    for (String stm : sql.getStatements()) {

        if (logger != null) {
            logger.debug(text.get("execute", myId, stm));
        }

        try {
            statement.execute(stm);
        } catch (SQLException e) {
            int sqlCode = e.getErrorCode();
            boolean accepted = false;
            int i = 0;
            while ((!accepted) && (i < acceptedSqlCodes.length)) {
                accepted = (acceptedSqlCodes[i] == sqlCode);
                i++;
            }
            if (!accepted) {
                try {
                    statement.close();
                } catch (SQLException ignore) {
                }
                throw e;
            }
        }
    }

    statement.close();
}

From source file:com.hangum.tadpole.rdb.core.editors.main.composite.MessageComposite.java

/**
 * SQLException to pretty message/*from   w w  w  . ja  va  2 s .c o m*/
 * 
 * @param sqlException
 * @param tadpoleMessageDAO
 * @return
 */
private String sqlExceptionToSearchMsg(SQLException sqlException, TadpoleMessageDAO tadpoleMessageDAO) {
    String strNewMessage = "";
    try {
        StringBuffer sbMsg = new StringBuffer();
        sbMsg.append(String.format(" %s %s", sqlException.getSQLState(), sqlException.getErrorCode()));
        //         sbMsg.append(String.format(" %s", sqlException.getMessage()));

        strNewMessage = sbMsg.toString();
    } catch (Exception e) {
        logger.error("SQLException to striing", e); //$NON-NLS-1$
        strNewMessage = tadpoleMessageDAO.getStrMessage();
    }

    return strNewMessage;
}

From source file:com.pontecultural.flashcards.ReadSpreadsheet.java

public void endElement(String uri, String localName, String qName) throws SAXException {
    if (qName.equals(TAG_FOR_TEXT)) {
        if (inSrcLang == true) {
            inSrcLang = false;/*from  ww w .j  a  va2  s.c  om*/
            srcColumnSetP = true;
        } else if (inDestLang == true) {
            inDestLang = false;
            srcColumnSetP = false;
        }
    } else if (qName.equals(TAG_FOR_CARD)) {
        if (!(srcPhrase.isEmpty() && destPhrase.isEmpty())) {
            if (inDescription) {
                logger.debug("deck name: " + deckName + " - " + destPhrase + "\n");
                Deck d = new Deck(deckName, destPhrase);
                try {
                    this.deckId = this.jdbcFlashcardsDao.insert(d);
                } catch (DataAccessException e) {
                    SQLException sqle = (SQLException) e.getCause();
                    logger.error(e.getCause().getMessage());
                    logger.error("Error code: " + sqle.getErrorCode());
                    logger.error("SQL state: " + sqle.getSQLState());
                }

                testCountDecks++;
            } else {
                Card c = new Card(srcPhrase, destPhrase, deckId);
                try {
                    this.jdbcFlashcardsDao.insert(c);
                } catch (DataAccessException e) {
                    SQLException sqle = (SQLException) e.getCause();
                    logger.error(e.getCause().getMessage());
                    logger.error("Error code: " + sqle.getErrorCode());
                    logger.error("SQL state: " + sqle.getSQLState());
                } catch (Exception e) {
                    logger.error("hmm..what happened here: " + e.getMessage());
                }
                logger.debug("card completed");
                logger.debug("\t en: " + srcPhrase);
                logger.debug("\t pt: " + destPhrase);
                testCountCards++;
            }
            this.initializeCardState();
        }
    } else if (qName.equals(TAG_FOR_DECK)) {
        logger.debug("deck completed.");
    }
}

From source file:churashima.action.manage.ExpensesAction.java

@Execute(input = "expenses.jsp")
public String entryExecute() {

    ExpensesDao expensesDao = SingletonS2Container.getComponent(ExpensesDao.class);
    SubjectDao subjectDao = SingletonS2Container.getComponent(SubjectDao.class);

    Expenses expenses = new Expenses();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    try {//  www.jav a 2  s  .co  m
        expenses.date = sdf.parse(expensesForm.strDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (expensesForm.subjectId == null) {
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.required", //??????
                new Object[] { "" }));
        ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);

        expensesForm.subjectList = subjectDao.selectForSearch(null, null);

        return "expenses.jsp";
    }

    expenses.subjectId = expensesForm.subjectId;
    expenses.place = expensesForm.place;
    expenses.name = expensesForm.name;
    expenses.comment = expensesForm.comment;
    expenses.category = expensesForm.category;
    expenses.categoryDetail = expensesForm.detail;
    expenses.openFlg = expensesForm.openFlg;
    expenses.isExcludeTax = expensesForm.isExcludeTax;

    TaxDao taxDao = SingletonS2Container.getComponent(TaxDao.class);
    BigDecimal tax = taxDao.selectByDate(expenses.date);

    if (Const.TAX_EXCLUDE.equals(expensesForm.isExcludeTax)) {
        // ?????
        expenses.priceTax = expensesForm.price.multiply(tax);
        expenses.priceExcludeTax = expensesForm.price;
        expenses.price = expenses.priceExcludeTax.add(expenses.priceTax);

    } else {
        // ????
        expenses.price = expensesForm.price;
        expenses.priceExcludeTax = expensesForm.price.divide(BigDecimal.valueOf(1).add(tax), 3,
                BigDecimal.ROUND_HALF_UP); // ?
        expenses.priceTax = expenses.price.subtract(expenses.priceExcludeTax);
    }

    // 
    Timestamp now = new Timestamp(System.currentTimeMillis());
    expenses.deleted = false;
    expenses.updDate = now;
    expenses.updId = null;
    expenses.insDate = now;
    expenses.insId = null;

    try {
        expensesDao.insert(expenses);
    } catch (SQLRuntimeException e) {
        SQLException e2 = (SQLException) e.getCause();
        if (e2.getErrorCode() == 0) {

            //???
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.already.entried", //??????
                    new Object[] { "????" }));
            ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);

            return "/manage/expenses";
        }
    }
    return "/manage/expenses";
}

From source file:com.norconex.collector.http.db.impl.derby.DerbyCrawlURLDatabase.java

private void sqlUpdate(String sql, Object... params) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("SQL: " + sql);
    }/*from  w ww .  j  a v a  2 s .  c o m*/
    try {
        new QueryRunner(datasource).update(sql, params);
    } catch (SQLException e) {
        if (e.getErrorCode() == SQL_ERROR_ALREADY_EXISTS) {
            LOG.debug("Already exists in table. SQL Error:" + e.getMessage());
        } else {
            throw new CrawlURLDatabaseException("Problem updating database.", e);
        }
    }
}

From source file:com.norconex.collector.core.data.store.impl.jdbc.JDBCCrawlDataStore.java

private boolean alreadyExists(SQLException e) {
    return (database == Database.DERBY && e.getErrorCode() == DERBY_ERROR_ALREADY_EXISTS)
            || (database == Database.H2 && e.getErrorCode() == H2_ERROR_ALREADY_EXISTS);
}