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:org.apache.sqoop.mapreduce.SQLServerAsyncDBExecThread.java

/**
 * Write the records to the database. If a failure occurs, it tries to
 * use the configured handler to recover from the failure, otherwise
 * a SQLException is throw//from   w  w  w .  j a v a  2s.  co m
 */
protected void write(List<SqoopRecord> records) throws SQLException, IOException {
    PreparedStatement stmt = null;
    int retryCount = RETRY_MAX;
    boolean doRetry = true;

    do {
        try {
            // Establish the connection to be used if not yet created
            getConnection();

            // Get the prepared statement to use for writing the records
            stmt = getPreparedStatement(records);

            // Execute the prepared statement
            executeStatement(stmt, records);

            // Statement executed successfully, no need to retry
            doRetry = false;
        } catch (SQLException sqlEx) {
            LOG.warn("Trying to recover from DB write failure: ", sqlEx);

            // Use configured connection handler to recover from the connection
            // failure and use the recovered connection.
            // If the failure cannot be recovered, an exception is thrown
            if (failureHandler.canHandleFailure(sqlEx)) {
                // Recover from connection failure
                this.conn = failureHandler.recover();

                // Configure the new connection before using it
                configureConnection();

                --retryCount;
                doRetry = (retryCount >= 0);
            } else {
                // Cannot recover using configured handler, re-throw
                throw new IOException("Registered handler cannot recover error " + "with SQL State: "
                        + sqlEx.getSQLState() + ", error code: " + sqlEx.getErrorCode(), sqlEx);
            }
        }
    } while (doRetry);

    // Throw an exception if all retry attempts are consumed
    if (retryCount < 0) {
        throw new IOException("Failed to write to database after " + RETRY_MAX + " retries.");
    }
}

From source file:com.frameworkset.platform.sanylog.action.CounterController.java

@SuppressWarnings("rawtypes")
public @ResponseBody String historyCompare(String tableName, String appId, String compareType, String startTime,
        String endTime) {/* ww  w. ja  va  2 s .c o  m*/
    try {
        List<OperRank> datas = new ArrayList<OperRank>();

        datas = counterManager.getOperRankForCompareByDay(appId, startTime, endTime, tableName);
        List<String> timeNodes = counterManager.getTimeNodes(startTime, endTime, tableName);
        List<String> moduleNodes = counterManager.getModuleNodes(appId, startTime, endTime, tableName);
        String caption = "";
        if ("count".equals(compareType)) {
            caption = "?";
        } else {
            caption = "?";
        }
        String dataXML = "<chart caption='" + caption + "' subcaption='' "
                + "lineThickness='1' showValues='0' formatNumberScale='0' anchorRadius='2'   "
                + "divLineAlpha='20' divLineColor='CC3300' divLineIsDashed='1' showAlternateHGridColor='1' "
                + "alternateHGridColor='CC3300' shadowAlpha='40' labelStep='2' "
                + "numvdivlines='5' chartRightMargin='35' bgColor='FFFFFF,CC3300' bgAngle='270' bgAlpha='10,10' "
                + "alternateHGridAlpha='5'  legendPosition ='RIGHT '>";
        /**
        */
        String categories = "<categories>";
        for (String timeNode : timeNodes) {//
            categories += "<category label='" + timeNode + "' />";
        }
        categories += "</categories>";
        dataXML = dataXML + categories;
        for (String moduleNode : moduleNodes) {//?
            String dataset = "<dataset seriesName='" + moduleNode + "'>";
            for (String timeNode : timeNodes) {
                boolean dupli = false;
                for (OperRank bean : datas) {
                    if (moduleNode.equals(bean.getModuleName()) && timeNode.equals(bean.getVtime())) {//??
                        if ("count".equals(compareType)) {
                            dataset += "<set value='" + bean.getVcount() + "' />";
                        } else {
                            dataset += "<set value='" + bean.getVcount() + "' />";
                        }
                        datas.remove(bean);
                        dupli = true;
                        break;
                    }
                }
                if (!dupli) {
                    dataset += "<set value='0' />";
                }
            }
            dataset += "</dataset>";
            dataXML = dataXML + dataset;
        }
        dataXML += "</chart>";
        return dataXML;
    } catch (SQLException e) {
        return e.getSQLState();
    }

}

From source file:pingpong.db.DBAccess.java

/**
 * Method executeQuery.//from  w w  w .ja  v  a  2 s  . c o  m
 * 
 * @param sql
 *             SQL
 * @param args
 *            SQL Statement?   ?
 * @param skipCount
 *            Skip Record
 * @param getCount
 *            Set ? Record
 * @return TResultSet Set
 * @throws SQLException
 */
public TResultSet executeQuery(String sql, Object[] args, int skipCount, int getCount) throws SQLException {
    Connection local_con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {

        log.debug(sql);

        if (m_con != null) {
            pstmt = m_con.prepareStatement(sql);
        } else {
            local_con = getConnection();
            pstmt = local_con.prepareStatement(sql);
        }
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                log.debug("arg " + i + " : " + args[i]);
                if (args[i] instanceof Null) {
                    pstmt.setNull(i + 1, ((Null) args[i]).type);
                } else {
                    pstmt.setObject(i + 1, args[i]);
                }
            }

        } else {
            log.debug("arg arg null");
        }

        rs = pstmt.executeQuery();
        state = 0;
        return makeTResultSet(rs, skipCount, getCount);
    } catch (SQLException e) {
        state = e.getErrorCode();
        sqlState = e.getSQLState();
        message = e.getMessage();
        throw e;
    } catch (Exception e) {
        message = e.getMessage();
        e.printStackTrace();
        return null;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (Exception e) {
            }
        }
        if (local_con != null) {
            try {
                local_con.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.archivas.clienttools.arcutils.utils.database.ManagedJobSchema.java

private void dropTable(Connection conn, String tableName) {
    Statement stmt = null;//w w w .j a va  2s .c  o m
    try {
        stmt = conn.createStatement();
        DBUtils.executeUpdate(stmt, "DROP TABLE " + tableName);
    } catch (SQLException sqle) {
        if ("42Y55".equalsIgnoreCase(sqle.getSQLState())) {
            // ignore this error, it means that the table did not exist
        } else {
            LOG.log(Level.WARNING, DBUtils.getErrorMessage("Failed to drop table " + tableName, sqle));
        }
    } catch (Exception e) {
        LOG.log(Level.WARNING, DBUtils.getErrorMessage("Failed to drop table " + tableName, e));
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:pingpong.db.DBAccess.java

/**
 * ResultSet?  ?  ? .// w w w. java2s  .  c o  m
 * @param sql
 * @param args
 * @return procedure?  rtn_cod, rtn_msg   String[]
 */
public String[] executeProcedure(String sql, Object args[]) throws SQLException {
    String result[] = { "", "" };
    Connection local_con = null;
    CallableStatement cstmt = null;
    ResultSet rs = null;
    int idxParam = (args == null) ? 0 : args.length;

    log.debug(sql);
    if (args != null) {
        for (int i = 0; i < args.length; i++) {
            log.debug("args" + i + ":" + args[i]);
        }
    }

    try {
        if (m_con != null) {
            cstmt = m_con.prepareCall(sql);
        } else {
            local_con = getConnection();
            cstmt = local_con.prepareCall(sql);
        }
        if (args != null) {

            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof Null) {
                    cstmt.setNull(i + 1, ((Null) args[i]).type);
                } else {
                    cstmt.setObject(i + 1, args[i]);
                }
            }
        }
        cstmt.setString(idxParam + 1, "");
        cstmt.setString(idxParam + 2, "");
        cstmt.registerOutParameter(idxParam + 1, Types.VARCHAR);
        cstmt.registerOutParameter(idxParam + 2, Types.VARCHAR);
        cstmt.execute();
        result[0] = cstmt.getString(idxParam + 1);
        result[1] = cstmt.getString(idxParam + 2);
    } catch (SQLException e) {
        state = e.getErrorCode();
        sqlState = e.getSQLState();
        message = e.getMessage();
        throw e;
    } catch (Exception e) {
        message = e.getMessage();
        e.printStackTrace();
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            }
        }
        if (cstmt != null) {
            try {
                cstmt.close();
            } catch (Exception e) {
            }
        }
        if (local_con != null) {
            try {
                local_con.close();
            } catch (Exception e) {
            }
        }
    }
    return result;
}

From source file:pingpong.db.DBAccess.java

public TResultSet executeProcedure1(String sql, Object args[]) throws SQLException {
    Connection local_con = null;/*w w w.j av a  2  s  .  c  om*/
    CallableStatement cstmt = null;
    ResultSet rs = null;
    TResultSet ds = null;

    sql = sql.replace(")", ",?)"); //
    log.debug("sql repalce:" + sql + "len:" + args.length);

    int idxParam = (args == null) ? 0 : args.length + 1;
    for (int i = 0; i < args.length; i++)
        log.debug("arg " + i + " : " + args[i]);
    try {
        if (m_con != null) {
            cstmt = m_con.prepareCall(sql);
        } else {
            local_con = getConnection();
            cstmt = local_con.prepareCall(sql);
        }
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                //log.debug("###########i: "+i +"/"+args[i]+"/"+args.length);
                if (args[i] instanceof Null) {
                    cstmt.setNull(i + 1, ((Null) args[i]).type);
                } else {
                    cstmt.setObject(i + 1, args[i]);
                }

            }

            // For Oracle Procedure return Cursor
            //            cstmt.registerOutParameter(idxParam, OracleTypes.CURSOR);  //            
        }

        // For Oracle Procedure
        //          cstmt.executeQuery();          
        //          rs = (ResultSet) cstmt.getObject(idxParam);
        rs = cstmt.executeQuery();

        return makeTResultSet(rs, 0, -1);
    } catch (SQLException e) {
        state = e.getErrorCode();
        sqlState = e.getSQLState();
        message = e.getMessage();
        throw e;
    } catch (Exception e) {
        message = e.getMessage();
        e.printStackTrace();
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            }
        }
        if (cstmt != null) {
            try {
                cstmt.close();
            } catch (Exception e) {
            }
        }
        if (local_con != null) {
            try {
                local_con.close();
            } catch (Exception e) {
            }
        }
    }
    return ds;
}

From source file:pingpong.db.DBAccess.java

/**
 * ResultSet?  ?  ? .//  w ww .  j a v a  2  s.c o m
 * @param args
 *       -  2? arguments   .
 * @return TResultSet? 
 */
public TResultSet executeProcedure2(String sql, Object args[]) throws SQLException {
    //      String result[] = {"", ""};
    Connection local_con = null;
    CallableStatement cstmt = null;
    ResultSet rs = null;
    TResultSet ds = null;

    //   sql.replace("?)", "?,?)");
    int idxParam = (args == null) ? 0 : args.length;
    try {
        if (m_con != null) {
            cstmt = m_con.prepareCall(sql);
        } else {
            local_con = getConnection();
            cstmt = local_con.prepareCall(sql);
        }
        if (args != null) {
            for (int i = 0; i < args.length - 2; i++) {
                if (args[i] instanceof Null) {
                    log.debug("1###########i:" + i + args[i]);

                    cstmt.setNull(i + 1, ((Null) args[i]).type);
                } else {
                    cstmt.setObject(i + 1, args[i]);
                    log.debug("2###########i:" + i + args[i]);
                }
            }
            cstmt.setString(idxParam - 1, "");
            cstmt.setString(idxParam, "");
            cstmt.registerOutParameter(idxParam - 1, Types.VARCHAR);
            cstmt.registerOutParameter(idxParam, Types.VARCHAR);
            //   cstmt.registerOutParameter(idxParam, OracleTypes.CURSOR);   
            log.debug("###########sql:" + sql + "\nargs:" + args + " len:" + args.length);
            log.debug("###########sql:" + sql + "\nargs:" + args + " len:" + args.length);
        }
        rs = cstmt.executeQuery();
        ds = new TResultSet(rs);
        args[idxParam - 2] = cstmt.getString(idxParam - 1);
        args[idxParam - 1] = cstmt.getString(idxParam);
    } catch (SQLException e) {
        state = e.getErrorCode();
        sqlState = e.getSQLState();
        message = e.getMessage();
        throw e;
    } catch (Exception e) {
        message = e.getMessage();
        e.printStackTrace();
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            }
        }
        if (cstmt != null) {
            try {
                cstmt.close();
            } catch (Exception e) {
            }
        }
        if (local_con != null) {
            try {
                local_con.close();
            } catch (Exception e) {
            }
        }
    }
    return ds;
}

From source file:pingpong.db.DBAccess.java

public TResultSet executeProcedure3(String sql, Object args[]) throws SQLException {
    Connection local_con = null;/* ww  w  .j a v  a2s .co  m*/
    CallableStatement cstmt = null;
    ResultSet rs = null;
    TResultSet ds = null;

    sql = sql.replace("?)", "?,?)"); //
    log.debug("sql repalce:" + sql);
    int idxParam = (args == null) ? 0 : args.length + 1;
    try {
        if (m_con != null) {
            cstmt = m_con.prepareCall(sql);
        } else {
            local_con = getConnection();
            cstmt = local_con.prepareCall(sql);
        }
        if (args != null) {
            for (int i = 0; i < args.length - 2; i++) {
                log.debug("###########i: " + i + "/" + args[i] + "/" + args.length);
                if (args[i] instanceof Null) {
                    cstmt.setNull(i + 1, ((Null) args[i]).type);
                } else {
                    cstmt.setObject(i + 1, args[i]);
                }
            }

            cstmt.setString(idxParam - 2, "");
            cstmt.setString(idxParam - 1, "");
            cstmt.registerOutParameter(idxParam - 2, Types.VARCHAR);
            cstmt.registerOutParameter(idxParam - 1, Types.VARCHAR);
            // For Oracle
            //            cstmt.registerOutParameter(idxParam, OracleTypes.CURSOR);  //

            log.debug("###########sql:" + sql + "\nargs:" + args + " len:" + args.length);
        }

        //OracleCallableStatement ? getCursor() method  REF CURSOR 
        //JDBC ResultSet variable ? .         
        //          cstmt.executeQuery();          
        //          rs = (ResultSet) cstmt.getObject(idxParam);
        rs = cstmt.executeQuery();
        ds = new TResultSet(rs);

        args[idxParam - 3] = cstmt.getString(idxParam - 2); //call by refenene  000
        args[idxParam - 2] = cstmt.getString(idxParam - 1); //O.K
        log.debug(cstmt.getString(idxParam - 2) + "," + cstmt.getString(idxParam - 1));
    } catch (SQLException e) {
        state = e.getErrorCode();
        sqlState = e.getSQLState();
        message = e.getMessage();
        throw e;
    } catch (Exception e) {
        message = e.getMessage();
        e.printStackTrace();
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            }
        }
        if (cstmt != null) {
            try {
                cstmt.close();
            } catch (Exception e) {
            }
        }
        if (local_con != null) {
            try {
                local_con.close();
            } catch (Exception e) {
            }
        }
    }
    return ds;
}

From source file:org.forgerock.openidm.repo.jdbc.impl.query.TableQueries.java

/**
 * Execute a query, either a pre-configured query by using the query ID, or
 * a query expression passed as part of the params.
 *
 * The keys for the input parameters as well as the return map entries are
 * in QueryConstants./*from  w  w  w .j av  a  2  s. c o  m*/
 *
 * @param type
 *            the resource component name targeted by the URI
 * @param params
 *            the parameters which include the query id, or the query
 *            expression, as well as the token key/value pairs to replace in
 *            the query
 * @param con
 *            a handle to a database connection newBuilder for exclusive use
 *            by the query method whilst it is executing.
 * @return The query result, which includes meta-data about the query, and
 *         the result set itself.
 * @throws BadRequestException
 *             if the passed request parameters are invalid, e.g. missing
 *             query id or query expression or tokens.
 * @throws InternalServerErrorException
 *             if the preparing or executing the query fails because of
 *             configuration or DB issues
 */
public List<Map<String, Object>> query(final String type, Map<String, Object> params, Connection con)
        throws ResourceException {

    List<Map<String, Object>> result = null;
    params.put(ServerConstants.RESOURCE_NAME, type);

    // If paged results are requested then decode the cookie in order to determine
    // the index of the first result to be returned.
    final int requestPageSize = (Integer) params.get(PAGE_SIZE);

    final String offsetParam;
    final String pageSizeParam;

    if (requestPageSize > 0) {
        offsetParam = String.valueOf((Integer) params.get(PAGED_RESULTS_OFFSET));
        pageSizeParam = String.valueOf(requestPageSize);
    } else {
        offsetParam = "0";
        pageSizeParam = String.valueOf(Integer.MAX_VALUE);
    }

    params.put(PAGED_RESULTS_OFFSET, offsetParam);
    params.put(PAGE_SIZE, pageSizeParam);
    QueryFilter<JsonPointer> queryFilter = (QueryFilter) params.get(QUERY_FILTER);
    String queryExpression = (String) params.get(QUERY_EXPRESSION);
    String queryId = (String) params.get(QUERY_ID);
    if (queryId == null && queryExpression == null && queryFilter == null) {
        throw new BadRequestException("Either " + QUERY_ID + ", " + QUERY_EXPRESSION + ", or " + QUERY_FILTER
                + " to identify/define a query must be passed in the parameters. " + params);
    }
    logger.debug("Querying " + params);
    final PreparedStatement foundQuery;
    try {
        if (queryFilter != null) {
            foundQuery = parseQueryFilter(con, queryFilter, params);
        } else if (queryExpression != null) {
            foundQuery = resolveInlineQuery(con, queryExpression, params);
        } else if (queries.queryIdExists(queryId)) {
            foundQuery = queries.getQuery(con, queryId, type, params);
        } else {
            throw new BadRequestException("The passed query identifier " + queryId
                    + " does not match any configured queries on the JDBC repository service.");
        }
    } catch (SQLException ex) {
        final String queryDescription;
        if (queryFilter != null) {
            queryDescription = queryFilter.toString();
        } else if (queryExpression != null) {
            queryDescription = queryExpression;
        } else {
            queryDescription = queries.getQueryInfo(queryId).getQueryString();
        }
        throw new InternalServerErrorException("DB reported failure preparing query: " + queryDescription
                + " with params: " + params + " error code: " + ex.getErrorCode() + " sqlstate: "
                + ex.getSQLState() + " message: " + ex.getMessage(), ex);
    }

    Name eventName = getEventName(queryId);
    EventEntry measure = Publisher.start(eventName, foundQuery, null);
    ResultSet rs = null;
    try {
        rs = foundQuery.executeQuery();
        result = resultMapper.mapQueryToObject(rs, queryId, type, params, this);
        measure.setResult(result);
    } catch (SQLException ex) {
        throw new InternalServerErrorException("DB reported failure executing query " + foundQuery.toString()
                + " with params: " + params + " error code: " + ex.getErrorCode() + " sqlstate: "
                + ex.getSQLState() + " message: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new InternalServerErrorException("Failed to convert result objects for query "
                + foundQuery.toString() + " with params: " + params + " message: " + ex.getMessage(), ex);
    } finally {
        CleanupHelper.loggedClose(rs);
        CleanupHelper.loggedClose(foundQuery);
        measure.end();
    }
    return result;
}

From source file:vitro.vspEngine.service.persistence.DBCommons.java

public Vector<String> getRegisteredGatewayRegNames() {
    Vector<String> retVect = new Vector<String>();
    java.sql.Connection conn = null;
    try {/*from   w w  w. j  ava  2  s.co m*/
        Class.forName(jdbcdriverClassName).newInstance();
        conn = DriverManager.getConnection(connString, usrStr, pwdStr);
        String echomessage = "";
        if (!conn.isClosed()) {
            //echomessage =  "Successfully connected to "+ "MySQL server using TCP/IP...";
            Statement stmt = null;
            ResultSet rs = null;
            try {
                stmt = conn.createStatement();
                if (stmt.execute("SELECT registeredName FROM `" + dbSchemaStr + "`.`registeredgateway` ")) {
                    rs = stmt.getResultSet();
                }
                if (rs != null) {
                    while (rs.next()) {
                        String registeredName = rs.getString("registeredName") == null ? ""
                                : rs.getString("registeredName");
                        if (!registeredName.isEmpty() && !registeredName.equalsIgnoreCase("")) {
                            retVect.add(registeredName);
                        }
                    }
                }
            } catch (SQLException ex) {
                // handle any errors
                System.err.println("SQLException2: " + ex.getMessage());
                System.err.println("SQLState2: " + ex.getSQLState());
                System.err.println("VendorError2: " + ex.getErrorCode());
            } finally {
                // it is a good idea to release
                // resources in a finally{} block
                // in reverse-order of their creation
                // if they are no-longer needed
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException sqlEx) {
                    } // ignore
                    rs = null;
                }
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException sqlEx) {
                    } // ignore
                    stmt = null;
                }
            }
        } else {
            echomessage = "Error accessing DB server...";
        }
        System.out.println(echomessage);
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
        }
    }
    return retVect;
}