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.skycloud.management.portal.admin.sysmanage.dao.impl.UserManageDaoImpl.java

@Override
public int saveSelfcaerUserInfo(final TUserBO user) throws SQLException {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    final String sql = "insert into T_SCS_COMPANY_USER(" + "ID,ACCOUNT,PWD," + "DEPT_ID,ROLE_ID,EMAIL,"
            + "POSITION,STATE," + "COMMENT,CHECK_CODE,IS_AUTO_APPROVE,CREATOR_USER_ID,"
            + "CREATE_DT,LASTUPDATE_DT) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
    try {//w w  w .java 2 s.c  o m
        this.getJdbcTemplate().update(new PreparedStatementCreator() {
            int i = 1;

            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setInt(i++, user.getId());
                ps.setString(i++, user.getAccount());
                ps.setString(i++, user.getPwd());
                //               ps.setString(i++, user.getName());
                ps.setInt(i++, user.getDeptId());
                ps.setInt(i++, user.getRoleId());
                ps.setString(i++, user.getEmail());
                ps.setString(i++, user.getPosition());
                ps.setInt(i++, user.getState());
                ps.setString(i++, user.getComment());
                ps.setString(i++, user.getCheckCode());
                ps.setInt(i++, user.getIsAutoApprove());
                ps.setInt(i++, user.getCreatorUserId());
                ps.setTimestamp(i++, new Timestamp(user.getCreateDt().getTime()));
                //update by CQ
                ps.setTimestamp(i++, new Timestamp(user.getLastupdateDt().getTime()));
                return ps;
            }
        }, keyHolder);
    } catch (Exception e) {
        throw new SQLException("??" + user.getComment() + " ID"
                + user.getCreatorUserId() + " " + user.getCreateDt() + " "
                + e.getMessage());
    }
    return keyHolder.getKey().intValue();
}

From source file:org.jfree.data.jdbc.JDBCCategoryDataset.java

/**
 * Populates the dataset by executing the supplied query against the
 * existing database connection.  If no connection exists then no action
 * is taken./*from  w w  w. j av a2  s.c  o m*/
 * <p>
 * The results from the query are extracted and cached locally, thus
 * applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param con  the connection.
 * @param query  the query.
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    Statement statement = null;
    ResultSet resultSet = null;
    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnCount = metaData.getColumnCount();

        if (columnCount < 2) {
            throw new SQLException("JDBCCategoryDataset.executeQuery() : insufficient columns "
                    + "returned from the database.");
        }

        // Remove any previous old data
        int i = getRowCount();
        while (--i >= 0) {
            removeRow(i);
        }

        while (resultSet.next()) {
            // first column contains the row key...
            Comparable rowKey = resultSet.getString(1);
            for (int column = 2; column <= columnCount; column++) {

                Comparable columnKey = metaData.getColumnName(column);
                int columnType = metaData.getColumnType(column);

                switch (columnType) {
                case Types.TINYINT:
                case Types.SMALLINT:
                case Types.INTEGER:
                case Types.BIGINT:
                case Types.FLOAT:
                case Types.DOUBLE:
                case Types.DECIMAL:
                case Types.NUMERIC:
                case Types.REAL: {
                    Number value = (Number) resultSet.getObject(column);
                    if (this.transpose) {
                        setValue(value, columnKey, rowKey);
                    } else {
                        setValue(value, rowKey, columnKey);
                    }
                    break;
                }
                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP: {
                    Date date = (Date) resultSet.getObject(column);
                    Number value = new Long(date.getTime());
                    if (this.transpose) {
                        setValue(value, columnKey, rowKey);
                    } else {
                        setValue(value, rowKey, columnKey);
                    }
                    break;
                }
                case Types.CHAR:
                case Types.VARCHAR:
                case Types.LONGVARCHAR: {
                    String string = (String) resultSet.getObject(column);
                    try {
                        Number value = Double.valueOf(string);
                        if (this.transpose) {
                            setValue(value, columnKey, rowKey);
                        } else {
                            setValue(value, rowKey, columnKey);
                        }
                    } catch (NumberFormatException e) {
                        // suppress (value defaults to null)
                    }
                    break;
                }
                default:
                    // not a value, can't use it (defaults to null)
                    break;
                }
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                // report this?
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                // report this?
            }
        }
    }
}

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

@Override
public void delete(Long id) throws SQLException {
    // delete addresses
    Company toDel = find(id);// w w w . j a  va  2s.c  om
    AddressDao adrDao = new AddressDao();
    try {
        init();
        for (Address adr : toDel.getAddresses()) {
            adrDao.delete(adr.getId(), conn);
        }
        st = conn.prepareStatement(SQL_DELETE_COMPANY);
        st.setLong(1, id);
        // run the query
        int i = st.executeUpdate();
        System.out.println("i: " + i);
        if (i == -1) {
            System.out.println("db error : " + SQL_DELETE_COMPANY);
        }
        conn.commit();
    } catch (Exception e) {
        // rollback the transaction but rethrow the exception to the caller
        conn.rollback();
        e.printStackTrace();
        throw new SQLException(e);
    } finally {
        close(conn, st, generatedKeys);
    }
}

From source file:com.googlecode.fascinator.sequences.SequenceService.java

/**
 * Check for the existence of a table and arrange for its creation if not
 * found./*from   w  w w.  j  a v  a2s  .  c  om*/
 * 
 * @param table
 *            The table to look for and create.
 * @throws SQLException
 *             if there was an error.
 */
private void checkTable(String table) throws SQLException {
    boolean tableFound = findTable(table);

    // Create the table if we couldn't find it
    if (!tableFound) {
        log.debug("Table '{}' not found, creating now!", table);
        createTable(table);

        // Double check it was created
        if (!findTable(table)) {
            log.error("Unknown error creating table '{}'", table);
            throw new SQLException("Could not find or create table '" + table + "'");
        }
    }
}

From source file:com.itemanalysis.psychometrics.rasch.JMLE.java

/**
 * Summarizes data into a TestFreqeuncyTable and stores scored responses in two way byte array
 * in a two way byte array.// w ww  .ja  va  2  s .  c o  m
 *
 * @throws SQLException
 */
public void summarizeData(ResultSet rs) throws SQLException {
    Object response = null;
    byte responseScore = 0;
    try {
        int r = 0;
        int c = 0;
        while (rs.next()) {
            c = 0;
            for (VariableAttributes v : variables) {//columns in data will be in same order as variables
                response = rs.getObject(v.getName().nameForDatabase());
                if ((response == null || response.equals("") || response.equals("NA")) && ignoreMissing) {
                    data[r][c] = -1;//code for omitted responses
                } else {
                    responseScore = (byte) v.getItemScoring().computeItemScore(response);
                    table.increment(v.getName(), v.getSubscale(true), responseScore);
                    data[r][c] = responseScore;
                }
                c++;
            }
            r++;
        }
    } catch (SQLException ex) {
        throw new SQLException(ex);
    }
}

From source file:io.cloudslang.content.database.services.databases.MSSqlDatabase.java

@Override
public List<String> setUp(@NotNull final SQLInputs sqlInputs) {
    try {/*from   w w  w.  j  a  v  a  2 s.c  o  m*/
        final List<String> dbUrls = new ArrayList<>();
        // todo ask eugen if need to check class
        if (sqlInputs.getDbClass() != null && sqlInputs.getDbClass().equals(SQLSERVER_JDBC_DRIVER)) {
            if (isNoneEmpty(sqlInputs.getDbUrl())) {
                final String dbUrl = MSSqlDatabase.addSslEncryptionToConnection(sqlInputs.isTrustAllRoots(),
                        sqlInputs.getTrustStore(), sqlInputs.getTrustStorePassword(), sqlInputs.getDbUrl());
                dbUrls.add(dbUrl);

            }
        }

        loadJdbcDriver(sqlInputs.getDbClass(), sqlInputs.getAuthenticationType(),
                sqlInputs.getAuthLibraryPath());

        String host;

        //compute the host value that will be used in the url
        String[] serverInstanceComponents = null;
        if (sqlInputs.getDbServer().contains(BACK_SLASH)) { //instance is included in the dbServer value
            serverInstanceComponents = sqlInputs.getDbServer().split("\\\\");
            host = serverInstanceComponents[0];
        } else {
            host = sqlInputs.getDbServer();
        }
        final Address address = new Address(host);
        host = address.getURIIPV6Literal();

        //instance is included in the host name
        //todo check if mssql dbName can be null, the other operation "supported" it
        if (isValidAuthType(sqlInputs.getAuthenticationType())) {
            final StringBuilder dbUrlMSSQL = new StringBuilder(Constants.MSSQL_URL + host + COLON
                    + sqlInputs.getDbPort() + SEMI_COLON + DATABASE_NAME_CAP + EQUALS + sqlInputs.getDbName());

            if (serverInstanceComponents != null) {
                dbUrlMSSQL.append(SEMI_COLON + INSTANCE + EQUALS).append(serverInstanceComponents[1]);
            } else if (isNoneEmpty(sqlInputs.getInstance())) {
                dbUrlMSSQL.append(SEMI_COLON + INSTANCE + EQUALS).append(sqlInputs.getInstance());
            }
            if (AUTH_WINDOWS.equalsIgnoreCase(sqlInputs.getAuthenticationType())) {
                dbUrlMSSQL.append(SEMI_COLON + INTEGRATED_SECURITY + EQUALS).append(TRUE);
            }
            final String connectionString = addSslEncryptionToConnection(sqlInputs.isTrustAllRoots(),
                    sqlInputs.getTrustStore(), sqlInputs.getTrustStorePassword(), dbUrlMSSQL.toString());
            //                sqlInputs.getDbUrls().add(connectionString);

            dbUrls.add(connectionString);

        } else {
            throw new SQLException(INVALID_AUTHENTICATION_TYPE_FOR_MS_SQL + sqlInputs.getAuthenticationType());
        }

        return dbUrls;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e.getCause());
    }
}

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

List<FuzzyCandidate<T>> loadFuzzyCandidates(List<Long> tuvIds, TM3Locale keyLocale) throws SQLException {
    if (tuvIds.size() == 0) {
        return Collections.emptyList();
    }/* w w  w.j  a  v a2s .  c  om*/
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT ").append("id, tuId, fingerprint, content").append(" FROM ")
            .append(getStorage().getTuvTableName()).append(" WHERE id IN").append(SQLUtil.longGroup(tuvIds));
    Connection conn = null;
    try {
        conn = DbUtil.getConnection();
        Statement s = conn.createStatement();
        ResultSet rs = SQLUtil.execQuery(s, sb.toString());

        List<FuzzyCandidate<T>> fuzzies = new ArrayList<FuzzyCandidate<T>>();
        while (rs.next()) {
            long id = rs.getLong(1);
            long tuId = rs.getLong(2);
            long fingerprint = rs.getLong(3);
            String content = rs.getString(4);
            TM3DataFactory<T> factory = getStorage().getTm().getDataFactory();
            fuzzies.add(new FuzzyCandidate<T>(id, tuId, fingerprint,
                    factory.fromSerializedForm(keyLocale, content)));
        }
        s.close();
        return fuzzies;
    } catch (Exception e) {
        throw new SQLException(e);
    } finally {
        DbUtil.silentReturnConnection(conn);
    }
}

From source file:org.apache.jena.jdbc.remote.connections.RemoteEndpointConnection.java

@Override
protected JenaPreparedStatement createPreparedStatementInternal(String sparql, int resultSetType,
        int resultSetConcurrency, int resultSetHoldability) throws SQLException {
    if (this.isClosed())
        throw new SQLException("Cannot create a statement after the connection was closed");
    if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE)
        throw new SQLFeatureNotSupportedException(
                "Remote endpoint backed connection do not support scroll sensitive result sets");
    if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY)
        throw new SQLFeatureNotSupportedException(
                "Remote endpoint backed connections only support read-only result sets");
    return new RemoteEndpointPreparedStatement(sparql, this, this.client, resultSetType,
            ResultSet.FETCH_FORWARD, 0, resultSetHoldability);
}

From source file:com.cws.esolutions.core.dao.impl.ApplicationDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IApplicationDataDAO#getApplicationsByAttribute(java.lang.String, int)
 *//* w ww  . j a  va  2 s  . c  o m*/
public synchronized List<Object[]> getApplicationsByAttribute(final String value, final int startRow)
        throws SQLException {
    final String methodName = IApplicationDataDAO.CNAME
            + "#getApplicationsByAttribute(final String value, final int startRow) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", value);
        DEBUGGER.debug("Value: {}", startRow);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object[]> responseData = null;

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);
        StringBuilder sBuilder = new StringBuilder();

        if (StringUtils.split(value, " ").length >= 2) {
            for (String str : StringUtils.split(value, " ")) {
                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", str);
                }

                sBuilder.append("+" + str);
                sBuilder.append(" ");
            }

            if (DEBUG) {
                DEBUGGER.debug("StringBuilder: {}", sBuilder);
            }
        } else {
            sBuilder.append("+" + value);
        }

        stmt = sqlConn.prepareCall("{CALL getApplicationByAttribute(?, ?)}");
        stmt.setString(1, sBuilder.toString().trim());
        stmt.setInt(2, startRow);

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

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

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

            if (resultSet.next()) {
                resultSet.beforeFirst();
                responseData = new ArrayList<Object[]>();

                while (resultSet.next()) {
                    Object[] data = new Object[] { resultSet.getString(1), // GUID
                            resultSet.getString(2), // NAME
                            resultSet.getInt(3) / 0 * 100 // score
                    };

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

                    responseData.add(data);
                }

                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", responseData);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

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

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return responseData;
}

From source file:com.cws.us.pws.dao.impl.ProductReferenceDAOImpl.java

/**
 * @see com.cws.us.pws.dao.interfaces.IProductReferenceDAO#getProductData(String, String) throws SQLException
 *//*from  w ww .j a va2 s.  co m*/
@Override
public List<Object> getProductData(final String productId, final String lang) throws SQLException {
    final String methodName = IProductReferenceDAO.CNAME
            + "#getProductData(final int productId, final String lang) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", productId);
        DEBUGGER.debug("Value: {}", lang);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    List<Object> results = null;
    CallableStatement stmt = null;

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

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

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

        stmt = sqlConn.prepareCall("{ CALL getProductData(?, ?) }");
        stmt.setString(1, productId);
        stmt.setString(2, lang);

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

        if (!(stmt.execute())) {
            throw new SQLException("PreparedStatement is null. Cannot execute.");
        }

        resultSet = stmt.getResultSet();

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

        if (resultSet.next()) {
            resultSet.beforeFirst();
            results = new ArrayList<Object>();

            while (resultSet.next()) {
                results.add(resultSet.getString(1)); // PRODUCT_ID
                results.add(resultSet.getString(2)); // PRODUCT_NAME
                results.add(resultSet.getString(3)); // PRODUCT_SHORT_DESC
                results.add(resultSet.getString(4)); // PRODUCT_DESC
                results.add(resultSet.getBigDecimal(5)); // PRODUCT_PRICE
                results.add(resultSet.getBoolean(6)); // IS_FEATURED
            }

            if (DEBUG) {
                DEBUGGER.debug("results: {}", results);
            }
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

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

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

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

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

    return results;
}