Example usage for java.sql SQLException SQLException

List of usage examples for java.sql SQLException SQLException

Introduction

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

Prototype

public SQLException(Throwable cause) 

Source Link

Document

Constructs a SQLException object with a given cause.

Usage

From source file:gridool.db.dba.DBAccessor.java

public Connection getPrimaryDbConnection() throws SQLException {
    try {//www  . ja v a2  s .c o  m
        return JDBCUtils.getConnection(primaryDbUrl, driverClassName, userName, password);
    } catch (ClassNotFoundException ce) {
        LOG.error(ce);
        throw new SQLException(ce);
    }
}

From source file:com.taobao.tddl.jdbc.group.TGroupStatement.java

private boolean executeInternal(String sql, int autoGeneratedKeys, int[] columnIndexes, String[] columnNames)
        throws SQLException {

    SqlType sqlType = SQLParser.getSqlType(sql);
    if (sqlType == SqlType.SELECT || sqlType == SqlType.SELECT_FOR_UPDATE || sqlType == SqlType.SHOW) {
        executeQuery(sql);//  w  w w.ja v  a 2s . c om
        return true;
    } else if (sqlType == SqlType.INSERT || sqlType == SqlType.UPDATE || sqlType == SqlType.DELETE
            || sqlType == SqlType.REPLACE || sqlType == SqlType.TRUNCATE || sqlType == SqlType.CREATE
            || sqlType == SqlType.DROP || sqlType == SqlType.LOAD || sqlType == SqlType.MERGE) {
        if (autoGeneratedKeys == -1 && columnIndexes == null && columnNames == null) {
            executeUpdate(sql);
        } else if (autoGeneratedKeys != -1) {
            executeUpdate(sql, autoGeneratedKeys);
        } else if (columnIndexes != null) {
            executeUpdate(sql, columnIndexes);
        } else if (columnNames != null) {
            executeUpdate(sql, columnNames);
        } else {
            executeUpdate(sql);
        }

        return false;
    } else {
        throw new SQLException(
                "only select, insert, update, delete,replace,truncate,create,drop,load,merge sql is supported");
    }
}

From source file:org.sakaiproject.orm.ibatis.support.AbstractLobTypeHandler.java

/**
 * This implementation always throws a SQLException:
 * retrieving LOBs from a CallableStatement is not supported.
 *///from w  ww  .j  av  a2s . c o m
public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
    throw new SQLException("Retrieving LOBs from a CallableStatement is not supported");
}

From source file:com.treasuredata.jdbc.TDResultSet.java

@Override
public ResultSetMetaData getMetaData() throws SQLException {
    try {/*w ww.  j a va 2  s . com*/
        JobSummary jobSummary = clientApi.waitJobResult(job);
        initColumnNamesAndTypes(jobSummary.getResultSchema());
        return new TDResultSetMetaData(job.getJobID(), columnNames, columnTypes);
    } catch (ClientException e) {
        throw new SQLException(e);
    }
}

From source file:it.larusba.neo4j.jdbc.http.HttpResultSet.java

@Override
public String getString(int columnIndex) throws SQLException {
    String object = null;// w w w . j  a  va2 s .co  m

    checkClosed();
    Object value = get(columnIndex);

    if (value != null) {
        final Class<?> type = value.getClass();

        if (String.class.equals(type)) {
            object = (String) value;
        } else {
            if (type.isPrimitive() || Number.class.isAssignableFrom(type)) {
                object = value.toString();
            } else {
                try {
                    object = OBJECT_MAPPER.writeValueAsString(value);
                } catch (Exception e) {
                    throw new SQLException("Couldn't convert value " + value + " of type " + type + " to JSON "
                            + e.getMessage());
                }
            }
        }
    }
    return object;
}

From source file:com.aoindustries.website.clientarea.accounting.EditCreditCardCompletedAction.java

@Override
public ActionForward executePermissionGranted(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response, SiteSettings siteSettings, Locale locale,
        Skin skin, AOServConnector aoConn) throws Exception {
    EditCreditCardForm editCreditCardForm = (EditCreditCardForm) form;

    String persistenceId = editCreditCardForm.getPersistenceId();
    if (GenericValidator.isBlankOrNull(persistenceId)) {
        // Redirect back to credit-card-manager if no persistenceId selected
        return mapping.findForward("credit-card-manager");
    }/*from  w  ww  .  ja v a  2  s .c  om*/
    int pkey;
    try {
        pkey = Integer.parseInt(persistenceId);
    } catch (NumberFormatException err) {
        getServlet().log(null, err);
        // Redirect back to credit-card-manager if persistenceId can't be parsed to int
        return mapping.findForward("credit-card-manager");
    }
    // Find the credit card
    CreditCard creditCard = aoConn.getCreditCards().get(pkey);
    if (creditCard == null) {
        // Redirect back to credit-card-manager if card no longer exists or is inaccessible
        return mapping.findForward("credit-card-manager");
    }

    // Validation
    ActionMessages errors = editCreditCardForm.validate(mapping, request);
    if (errors != null && !errors.isEmpty()) {
        saveErrors(request, errors);
        // Init request values before showing input
        initRequestAttributes(request, getServlet().getServletContext());
        request.setAttribute("creditCard", creditCard);
        return mapping.findForward("input");
    }

    // Tells the view layer what was updated
    boolean updatedCardDetails = false;
    boolean updatedCardNumber = false;
    boolean updatedExpirationDate = false;
    boolean reactivatedCard = false;

    if (!nullOrBlankEquals(editCreditCardForm.getFirstName(), creditCard.getFirstName())
            || !nullOrBlankEquals(editCreditCardForm.getLastName(), creditCard.getLastName())
            || !nullOrBlankEquals(editCreditCardForm.getCompanyName(), creditCard.getCompanyName())
            || !nullOrBlankEquals(editCreditCardForm.getStreetAddress1(), creditCard.getStreetAddress1())
            || !nullOrBlankEquals(editCreditCardForm.getStreetAddress2(), creditCard.getStreetAddress2())
            || !nullOrBlankEquals(editCreditCardForm.getCity(), creditCard.getCity())
            || !nullOrBlankEquals(editCreditCardForm.getState(), creditCard.getState())
            || !nullOrBlankEquals(editCreditCardForm.getPostalCode(), creditCard.getPostalCode())
            || !nullOrBlankEquals(editCreditCardForm.getCountryCode(), creditCard.getCountryCode().getCode())
            || !nullOrBlankEquals(editCreditCardForm.getDescription(), creditCard.getDescription())) {
        // Update all fields except card number and expiration
        // Root connector used to get processor
        AOServConnector rootConn = siteSettings.getRootAOServConnector();
        CreditCard rootCreditCard = rootConn.getCreditCards().get(creditCard.getPkey());
        if (rootCreditCard == null)
            throw new SQLException("Unable to find CreditCard: " + creditCard.getPkey());
        CreditCardProcessor rootProcessor = CreditCardProcessorFactory
                .getCreditCardProcessor(rootCreditCard.getCreditCardProcessor());
        com.aoindustries.creditcards.CreditCard storedCreditCard = CreditCardFactory
                .getCreditCard(rootCreditCard);
        // Update fields
        storedCreditCard.setFirstName(editCreditCardForm.getFirstName());
        storedCreditCard.setLastName(editCreditCardForm.getLastName());
        storedCreditCard.setCompanyName(editCreditCardForm.getCompanyName());
        storedCreditCard.setStreetAddress1(editCreditCardForm.getStreetAddress1());
        storedCreditCard.setStreetAddress2(editCreditCardForm.getStreetAddress2());
        storedCreditCard.setCity(editCreditCardForm.getCity());
        storedCreditCard.setState(editCreditCardForm.getState());
        storedCreditCard.setPostalCode(editCreditCardForm.getPostalCode());
        storedCreditCard.setCountryCode(editCreditCardForm.getCountryCode());
        storedCreditCard.setComments(editCreditCardForm.getDescription());
        // Update persistence
        rootProcessor.updateCreditCard(
                new AOServConnectorPrincipal(rootConn,
                        aoConn.getThisBusinessAdministrator().getUsername().getUsername().toString()),
                storedCreditCard);
        updatedCardDetails = true;
    }

    String newCardNumber = editCreditCardForm.getCardNumber();
    String newExpirationMonth = editCreditCardForm.getExpirationMonth();
    String newExpirationYear = editCreditCardForm.getExpirationYear();
    String newCardCode = editCreditCardForm.getCardCode();
    if (!GenericValidator.isBlankOrNull(newCardNumber)) {
        // Update card number and expiration
        // Root connector used to get processor
        AOServConnector rootConn = siteSettings.getRootAOServConnector();
        CreditCard rootCreditCard = rootConn.getCreditCards().get(creditCard.getPkey());
        if (rootCreditCard == null)
            throw new SQLException("Unable to find CreditCard: " + creditCard.getPkey());
        CreditCardProcessor rootProcessor = CreditCardProcessorFactory
                .getCreditCardProcessor(rootCreditCard.getCreditCardProcessor());
        rootProcessor.updateCreditCardNumberAndExpiration(
                new AOServConnectorPrincipal(rootConn,
                        aoConn.getThisBusinessAdministrator().getUsername().getUsername().toString()),
                CreditCardFactory.getCreditCard(rootCreditCard), newCardNumber,
                Byte.parseByte(newExpirationMonth), Short.parseShort(newExpirationYear), newCardCode);
        updatedCardNumber = true;
        updatedExpirationDate = true;
    } else {
        if (!GenericValidator.isBlankOrNull(newExpirationMonth)
                && !GenericValidator.isBlankOrNull(newExpirationYear)) {
            // Update expiration only
            // Root connector used to get processor
            AOServConnector rootConn = siteSettings.getRootAOServConnector();
            CreditCard rootCreditCard = rootConn.getCreditCards().get(creditCard.getPkey());
            if (rootCreditCard == null)
                throw new SQLException("Unable to find CreditCard: " + creditCard.getPkey());
            CreditCardProcessor rootProcessor = CreditCardProcessorFactory
                    .getCreditCardProcessor(rootCreditCard.getCreditCardProcessor());
            rootProcessor
                    .updateCreditCardExpiration(
                            new AOServConnectorPrincipal(rootConn,
                                    aoConn.getThisBusinessAdministrator().getUsername().getUsername()
                                            .toString()),
                            CreditCardFactory.getCreditCard(rootCreditCard), Byte.parseByte(newExpirationMonth),
                            Short.parseShort(newExpirationYear));
            updatedExpirationDate = true;
        }
    }

    if (!creditCard.getIsActive()) {
        // Reactivate if not active
        creditCard.reactivate();
        reactivatedCard = true;
    }

    // Set the cardNumber request attribute
    String cardNumber;
    if (!GenericValidator.isBlankOrNull(editCreditCardForm.getCardNumber()))
        cardNumber = com.aoindustries.creditcards.CreditCard
                .maskCreditCardNumber(editCreditCardForm.getCardNumber());
    else
        cardNumber = creditCard.getCardInfo();
    request.setAttribute("cardNumber", cardNumber);

    // Store which steps were done
    request.setAttribute("updatedCardDetails", updatedCardDetails ? "true" : "false");
    request.setAttribute("updatedCardNumber", updatedCardNumber ? "true" : "false");
    request.setAttribute("updatedExpirationDate", updatedExpirationDate ? "true" : "false");
    request.setAttribute("reactivatedCard", reactivatedCard ? "true" : "false");

    return mapping.findForward("success");
}

From source file:com.nortal.petit.converter.util.ResultSetHelper.java

public static Object get(Type type, ResultSet rs, String column) throws SQLException {
    try {//from   ww  w  .  jav  a2s .  c  om
        ColumnRetrievalStrategy<?> strategy = type == null ? new NopColumnRetrievalStrategy()
                : type.getColumnRetrievalStrategy();

        return strategy.getColumnValue(rs, column);

    } catch (SQLException e) {
        SQLException exception = new SQLException("Failed to get data from column " + column);
        e.setNextException(exception);
        throw e;
    }
}

From source file:com.softberries.klerk.dao.AddressDao.java

public void update(Address c, QueryRunner run, Connection conn) throws SQLException {
    PreparedStatement st = conn.prepareStatement(SQL_UPDATE_ADDRESS);
    st.setString(1, c.getCountry());//ww  w .j a va2s .  com
    st.setString(2, c.getCity());
    st.setString(3, c.getStreet());
    st.setString(4, c.getPostCode());
    st.setString(5, c.getHouseNumber());
    st.setString(6, c.getFlatNumber());
    st.setString(7, c.getNotes());
    st.setBoolean(8, c.isMain());
    if (c.getPerson_id() == null && c.getCompany_id() == null) {
        throw new SQLException("Either Person or Company needs to be specified");
    }
    if (c.getPerson_id().longValue() != 0) {
        st.setLong(9, c.getPerson_id());
    } else {
        st.setNull(9, java.sql.Types.NUMERIC);
    }
    if (c.getCompany_id().longValue() != 0) {
        st.setLong(10, c.getCompany_id());
    } else {
        st.setNull(10, java.sql.Types.NUMERIC);
    }
    st.setLong(11, c.getId());
    // run the query
    int i = st.executeUpdate();
    System.out.println("i: " + i);
    if (i == -1) {
        System.out.println("db error : " + SQL_UPDATE_ADDRESS);
    }
}

From source file:com.github.tosdan.utils.sql.MyQueryRunner.java

/**
* Calls update after checking the parameters to ensure nothing is null.
* @param conn The connection to use for the batch call.
* @param closeConn True if the connection should be closed, false otherwise.
* @param sql The SQL statement to execute.
* @param params An array of query replacement parameters.  Each row in
* this array is one set of batch replacement values.
* @return The number of rows updated in the batch.
* @throws SQLException If there are database or parameter errors.
*//*from ww  w.j ava 2 s. c  o m*/
private int[] batch(Connection conn, boolean closeConn, String sql, Object[][] params) throws SQLException {
    if (conn == null) {
        throw new SQLException("Null connection");
    }

    if (sql == null) {
        if (closeConn) {
            close(conn);
        }
        throw new SQLException("Null SQL statement");
    }

    if (params == null) {
        if (closeConn) {
            close(conn);
        }
        throw new SQLException("Null parameters. If parameters aren't need, pass an empty array.");
    }

    PreparedStatement stmt = null;
    int[] rows = null;
    try {
        stmt = this.prepareStatement(conn, sql);

        for (int i = 0; i < params.length; i++) {
            this.fillStatement(stmt, params[i]);
            stmt.addBatch();
        }
        rows = stmt.executeBatch();

    } catch (SQLException e) {
        this.rethrow(e, sql, (Object[]) params);
    } finally {
        close(stmt);
        if (closeConn) {
            close(conn);
        }
    }

    return rows;
}

From source file:edu.corgi.uco.UserBean.java

public String add() throws SQLException, EmailException {

    if (dataSource == null) {
        throw new SQLException("DataSource is null");
    }/*from  w  ww .ja  va  2  s .c o  m*/

    Connection connection = dataSource.getConnection();

    if (connection == null) {
        throw new SQLException("Connection");
    }

    try {

        Random rand = new Random();
        int randomNum = rand.nextInt((999999999 - 100000000) + 1) + 100000000;

        PreparedStatement addUser = connection.prepareStatement(
                "insert into UserTable (email, ucoID, password, firstName, lastName,authKey) values (?, ?, ?, ?, ?,?)",
                Statement.RETURN_GENERATED_KEYS);

        addUser.setString(1, email);
        addUser.setString(2, ucoId);
        addUser.setString(3, password);
        addUser.setString(4, firstName);
        addUser.setString(5, lastName);
        addUser.setInt(6, randomNum);

        addUser.executeUpdate();

        ResultSet results = addUser.getGeneratedKeys();

        //for whatever really fun reason it says userid is not a field
        int id = 0;
        while (results.next()) {
            id = results.getInt(1);
        }

        PreparedStatement addUserToGroup = connection
                .prepareStatement("insert into GroupTable (userID, email) values (?, ?)");

        addUserToGroup.setInt(1, id);
        addUserToGroup.setString(2, email);

        addUserToGroup.executeUpdate();

        PreparedStatement addMajor = connection
                .prepareStatement("insert into MajorCodes (userID, majorCode) values (?, ?)");

        addMajor.setInt(1, id);
        addMajor.setString(2, major);

        addMajor.executeUpdate();
        sendEmails send = new sendEmails();
        send.sendConfirmation(email, firstName, lastName, randomNum, id);
        System.out.print("test");

    } finally {
        connection.close();
    }

    return "thanks";
}