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:com.tesora.dve.dbc.ServerDBConnection.java

public int executeUpdate(byte[] sql) throws SQLException {
    initialize();// www  .j  a  v a 2s .  c  o m

    final MysqlTextResultCollector resultConsumer = new MysqlTextResultCollector();
    try {
        executeInContext(resultConsumer, sql);

        // Not the most optimal but it's the quickest way to use rows affected vs rows changed settings
        int ret = (int) resultConsumer.getNumRowsAffected();
        if (ret == 0 && resultConsumer.getInfoString() != null
                && !StringUtils.startsWithIgnoreCase(resultConsumer.getInfoString(), "Rows matched: 0")) {
            int start = StringUtils.indexOf(resultConsumer.getInfoString(), "Rows matched: ")
                    + "Rows matched: ".length();
            int end = StringUtils.indexOf(resultConsumer.getInfoString(), "Changed:");
            try {
                ret = Integer.valueOf(StringUtils.substring(resultConsumer.getInfoString(), start, end).trim());
            } catch (Exception e) {
                // do nothing take original value
            }
        }

        return ret;
    } catch (SchemaException se) {
        throw ErrorMapper.makeException(se);
    } catch (Throwable t) {
        throw new SQLException(t);
    } finally {
        ssCon.releaseNonTxnLocks();
    }
}

From source file:com.globalsight.ling.tm3.core.TuStorage.java

/**
 * Deletes one or more TUs, along with all their TUVs, attributes, and
 * history./*from ww w . ja  v  a 2 s .  c o  m*/
 * 
 * @param ids
 *            List of TU ids to delete
 * @throws SQLException
 */
public void deleteTusById(List<Long> ids) throws SQLException {
    if (ids.size() == 0) {
        return;
    }
    Connection conn = null;
    try {
        conn = DbUtil.getConnection();
        conn.setAutoCommit(false);
        SQLUtil.exec(conn, new StatementBuilder().append("DELETE FROM ").append(storage.getTuTableName())
                .append(" WHERE id IN ").append(SQLUtil.longGroup(ids)));
        conn.commit();
    } catch (Exception e) {
        throw new SQLException(e);
    } finally {
        DbUtil.silentReturnConnection(conn);
    }
}

From source file:it.cnr.icar.eric.server.persistence.rdb.ConnectionPool.java

private synchronized Connection getConnection(String contextId, long timeout) throws SQLException {
    // Get a pooled Connection from the cache or a new one.
    // Wait if all are checked out and the max limit has
    // been reached.
    long startTime = System.currentTimeMillis();
    long remaining = timeout;
    Connection conn = null;/*w  w  w .j  ava2s.  c o  m*/

    while ((conn = getPooledConnection(contextId)) == null) {
        try {
            wait(remaining);
        } catch (InterruptedException e) {
        }

        remaining = timeout - (System.currentTimeMillis() - startTime);

        if (remaining <= 0) {
            // Timeout has expired
            throw new SQLException(
                    ServerResourceBundle.getInstance().getString("message.databaseConnectionTimedOut"));
        }
    }

    // Check if the Connection is still OK
    if (!isConnectionOK(conn)) {
        // It was bad. Try again with the remaining timeout
        return getConnection(contextId, remaining);
    }

    //Got a good connection
    checkedOutConnections.put(conn, contextId);

    return conn;
}

From source file:org.ohmage.query.impl.UserImageQueries.java

@Override
public Collection<URL> getImageUrlsFromUsername(String username) throws DataAccessException {

    try {/*from   www  .  j  a v a 2 s. co m*/
        return getJdbcTemplate().query(SQL_GET_URLS_FOR_ALL_IMAGE_RESPONSES_FOR_USER, new Object[] { username },
                new RowMapper<URL>() {
                    /**
                     * Converts the URL string to a URL object.
                     */
                    @Override
                    public URL mapRow(ResultSet rs, int rowNum) throws SQLException {

                        try {
                            return new URL(rs.getString("url"));
                        } catch (MalformedURLException e) {
                            throw new SQLException(
                                    "The URL in the database is malformed: " + rs.getString("url"));
                        }
                    }
                });

    } catch (org.springframework.dao.DataAccessException e) {
        throw new DataAccessException("Error executing SQL '" + SQL_GET_URLS_FOR_ALL_IMAGE_RESPONSES_FOR_USER
                + "' with parameter: " + username, e);
    }
}

From source file:co.nubetech.apache.hadoop.DateSplitter.java

/**
 * Retrieve the value from the column in a type-appropriate manner and
 * return its timestamp since the epoch. If the column is null, then return
 * Long.MIN_VALUE. This will cause a special split to be generated for the
 * NULL case, but may also cause poorly-balanced splits if most of the
 * actual dates are positive time since the epoch, etc.
 *//*from  w ww .  j  a va  2  s. c  om*/
private long resultSetColToLong(ResultSet rs, int colNum, int sqlDataType) throws SQLException {
    try {
        switch (sqlDataType) {
        case Types.DATE:
            return rs.getDate(colNum).getTime();
        case Types.TIME:
            return rs.getTime(colNum).getTime();
        case Types.TIMESTAMP:
            return rs.getTimestamp(colNum).getTime();
        default:
            throw new SQLException("Not a date-type field");
        }
    } catch (NullPointerException npe) {
        // null column. return minimum long value.
        LOG.warn("Encountered a NULL date in the split column. Splits may be poorly balanced.");
        return Long.MIN_VALUE;
    }
}

From source file:com.cloudera.sqoop.mapreduce.db.DateSplitter.java

/**
    Retrieve the value from the column in a type-appropriate manner and
    return its timestamp since the epoch. If the column is null, then return
    Long.MIN_VALUE.  This will cause a special split to be generated for the
    NULL case, but may also cause poorly-balanced splits if most of the
    actual dates are positive time since the epoch, etc.
  *///from  w ww . j av a 2s . c  o m
private long resultSetColToLong(ResultSet rs, int colNum, int sqlDataType) throws SQLException {
    try {
        switch (sqlDataType) {
        case Types.DATE:
            return rs.getDate(colNum).getTime();
        case Types.TIME:
            return rs.getTime(colNum).getTime();
        case Types.TIMESTAMP:
            return rs.getTimestamp(colNum).getTime();
        default:
            throw new SQLException("Not a date-type field");
        }
    } catch (NullPointerException npe) {
        // null column. return minimum long value.
        LOG.warn("Encountered a NULL date in the split column. " + "Splits may be poorly balanced.");
        return Long.MIN_VALUE;
    }
}

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

/**
 * Executes SQL provided as <tt>Sql</tt> instance immediately.
 * <p>//  w  w w  .  j a v  a2  s.  c  o  m
 * 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.cws.esolutions.security.dao.userauth.impl.SQLAuthenticator.java

/**
 * @see com.cws.esolutions.security.dao.userauth.interfaces.Authenticator#obtainSecurityData(java.lang.String, java.lang.String)
 *//*from   www  .  j av  a  2  s .  co m*/
public synchronized List<String> obtainSecurityData(final String userName, final String userGuid)
        throws AuthenticatorException {
    final String methodName = SQLAuthenticator.CNAME
            + "#obtainSecurityData(final String userName, final String userGuid) throws AuthenticatorException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", userName);
        DEBUGGER.debug("Value: {}", userGuid);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<String> userSecurity = null;

    try {
        sqlConn = SQLAuthenticator.dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{CALL getUserByAttribute(?, ?)}");
        stmt.setString(1, userName); // guid
        stmt.setInt(2, 0); // count

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("ResultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();

                while (resultSet.next()) {
                    if (StringUtils.equals(resultSet.getString(2), userName)) {
                        String cn = resultSet.getString(1);
                        String username = resultSet.getString(2);

                        if (DEBUG) {
                            DEBUGGER.debug("String: {}", cn);
                            DEBUGGER.debug("String: {}", username);
                        }

                        resultSet.close();
                        stmt.close();

                        // found the user we want
                        stmt = sqlConn.prepareCall("{ CALL getSecurityQuestions(?, ?) }");
                        stmt.setString(1, username); // common name
                        stmt.setString(2, cn);

                        if (DEBUG) {
                            DEBUGGER.debug("CallableStatement: {}", stmt);
                        }

                        if (stmt.execute()) {
                            resultSet = stmt.getResultSet();

                            if (DEBUG) {
                                DEBUGGER.debug("ResultSet: {}", resultSet);
                            }

                            if (resultSet.next()) {
                                userSecurity = new ArrayList<String>(
                                        Arrays.asList(resultSet.getString(1), resultSet.getString(2)));

                                if (DEBUG) {
                                    DEBUGGER.debug("userSecurity: {}", userSecurity);
                                }
                            }
                        }
                    }
                }

            }
        }
    } catch (SQLException sqx) {
        throw new AuthenticatorException(sqx.getMessage(), sqx);
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

            if (stmt != null) {
                stmt.close();
            }

            if (!(sqlConn == null) && (!(sqlConn.isClosed()))) {
                sqlConn.close();
            }
        } catch (SQLException sqx) {
            throw new AuthenticatorException(sqx.getMessage(), sqx);
        }
    }

    return userSecurity;
}

From source file:com.taobao.adfs.database.tdhsocket.client.util.ConvertUtil.java

public static BigDecimal getBigDecimalFromString(String stringVal) throws SQLException {
    BigDecimal val;
    if (stringVal != null) {
        if (stringVal.length() == 0) {
            val = new BigDecimal("0");
            return val;
        }/*from w  w  w  .  j  a  v  a2s. c o  m*/
        try {
            val = new BigDecimal(stringVal);
            return val;
        } catch (NumberFormatException ex) {
            throw new SQLException("ResultSet.Bad_format_for_BigDecimal: value=" + stringVal);
        }
    }
    return null;
}

From source file:com.qubole.quark.plugins.jdbc.JdbcDB.java

private ImmutableMap<String, Schema> getSchemaFromResultSet(ResultSet rs,
        ImmutableMap<String, Integer> dataTypes) throws SQLException {
    if (rs == null || !rs.next()) {
        return ImmutableMap.of();
    }//from w w w .ja v a  2  s  . com
    ImmutableMap.Builder<String, Schema> schemaBuilder = new ImmutableMap.Builder<>();

    while (!rs.isAfterLast()) {
        String currentSchema = rs.getString(1);
        ImmutableMap.Builder<String, Table> tableBuilder = new ImmutableMap.Builder<>();
        while (!rs.isAfterLast() && rs.getString(1).equals(currentSchema)) {
            ImmutableList.Builder<QuarkColumn> columnBuilder = new ImmutableList.Builder<>();
            String currentTable = rs.getString(2);
            while (rs.getString(2).equals(currentTable)) {
                String columnName = rs.getString(3);
                if (!this.isCaseSensitive()) {
                    columnName = columnName.toUpperCase();
                }
                Integer dataType = null;
                for (String key : dataTypes.keySet()) {
                    if (rs.getString(4).toUpperCase().matches(key)) {
                        dataType = dataTypes.get(key);
                        break;
                    }
                }
                if (dataType == null) {
                    throw new SQLException("DataType `" + rs.getString(4) + "` is not supported");
                }
                columnBuilder.add(new QuarkColumn(columnName, dataType));
                LOG.debug("Adding column:  " + rs.getString(1) + " : " + rs.getString(2) + " : "
                        + rs.getString(3) + " : " + rs.getString(4));
                if (!rs.next()) {
                    break;
                }
            }

            if (!this.isCaseSensitive()) {
                currentTable = currentTable.toUpperCase();
            }
            tableBuilder.put(currentTable, new QuarkTable(columnBuilder.build()));
        }
        if (!this.isCaseSensitive()) {
            currentSchema = currentSchema.toUpperCase();
        }

        schemaBuilder.put(currentSchema,
                new com.qubole.quark.plugins.SimpleSchema(currentSchema.toUpperCase(), tableBuilder.build()));
    }
    return schemaBuilder.build();
}