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:bdManager.DBConnectionManager.java

public void closeConnection() throws SQLException {
    long threadID = Thread.currentThread().getId();
    Connection connection = this.connections.get(threadID);

    if (connection != null) {
        if (!connection.isClosed()) {
            connection.close();/*  ww w  .  ja  v  a  2 s  .co m*/
        }
        this.connections.remove(threadID);
    } else {
        throw new SQLException("Session for thread " + threadID + " is not opened.");
    }
}

From source file:herddb.jdbc.BasicHerdDBDataSource.java

protected synchronized void doWaitForTableSpace() throws SQLException {
    if (waitForTableSpaceTimeout > 0 && !waitForTableSpace.isEmpty()) {
        try (HDBConnection con = client.openConnection();) {
            con.waitForTableSpace(waitForTableSpace, waitForTableSpaceTimeout);
        } catch (HDBException err) {
            throw new SQLException(err);
        }/*from   www  .  j  a  v a 2s.  c  o  m*/
    }
}

From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableKeys.java

/**
 * Obtain from the database a list of tables' primary keys.
 * //from   www.j av a2 s  .  c  o m
 * @return A list of {@link UniqueKey} object represented foreign keys.
 * @throws SQLException
 *             Is thrown in case any errors during work with database occur.
 */
@SuppressWarnings("unchecked")
public Set<UniqueKey> getPrimaryKeys() throws SQLException {
    if (primaryKeys != null) {
        return primaryKeys;
    }
    Set<UniqueKey> tablePrimaryKeySet = null;
    try {
        tablePrimaryKeySet = (Set<UniqueKey>) JdbcUtils.extractDatabaseMetaData(dataSource,
                new KeyListProcessor(tableName, new TableKeyPerformer() {
                    @Override
                    public ResultSet getResultSet(DatabaseMetaData dmd, String tableName) throws SQLException {
                        return dmd.getPrimaryKeys(null, null, tableName);
                    }

                    @Override
                    public void addKeyToSet(ResultSet rs, Set<TableKey> keySet) throws SQLException {
                        if (rs.getString(PK_NAME) != null && rs.getString(COLUMN_NAME) != null) {
                            keySet.add(new UniqueKey(rs.getString(PK_NAME), rs.getString(COLUMN_NAME)));
                        }

                    }
                }));
    } catch (MetaDataAccessException e) {
        throw new SQLException(e);
    }
    primaryKeys = tablePrimaryKeySet;
    return tablePrimaryKeySet;
}

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

@Override
public void create(Product p) throws SQLException {
    try {/*www .  ja va 2 s.  c o  m*/
        init();
        st = conn.prepareStatement(SQL_INSERT_PRODUCT, Statement.RETURN_GENERATED_KEYS);
        st.setString(1, p.getCode());
        st.setString(2, p.getName());
        st.setString(3, p.getDescription());
        // run the query
        int i = st.executeUpdate();
        System.out.println("i: " + i);
        if (i == -1) {
            System.out.println("db error : " + SQL_INSERT_PRODUCT);
        }
        generatedKeys = st.getGeneratedKeys();
        if (generatedKeys.next()) {
            p.setId(generatedKeys.getLong(1));
        } else {
            throw new SQLException("Creating user failed, no generated key obtained.");
        }
        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.skycloud.management.portal.admin.sysmanage.dao.impl.UserManageDaoImpl.java

@Override
public int saveSelfcaerUser(final TUserBO user) throws SQLException {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    final String sql = "insert into T_SCS_USER(" + "ID,ACCOUNT,PWD," + "DEPT_ID,ROLE_ID,EMAIL,"
            + "POSITION,STATE," + "COMMENT,CHECK_CODE,IS_AUTO_APPROVE,CREATOR_USER_ID,"
            + "CREATE_DT,LASTUPDATE_DT,COMP_ID,MOBILE) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
    try {/*from   w  w  w  .  ja  va 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()));
                ps.setInt(i++, user.getCompId());
                ps.setString(i++, user.getMobile());
                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:com.aliyun.odps.jdbc.OdpsForwardResultSet.java

protected Object[] rowAtCursor() throws SQLException {
    if (currentRow == null) {
        throw new SQLException("the row should be not-null, row=" + fetchedRows);
    }//from  w w  w. ja v  a2s .c  o  m

    if (currentRow.length == 0) {
        throw new SQLException("the row should have more than 1 column , row=" + fetchedRows);
    }

    return currentRow;
}

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

private ClientAPI.ExtUnpacker fetchRows() throws SQLException {
    JobSummary jobSummary = null;/* w  w  w. ja va2  s  .c o  m*/

    Callable<JobSummary> callback = new Callable<JobSummary>() {
        @Override
        public JobSummary call() throws Exception {
            JobSummary jobSummary = clientApi.waitJobResult(job);
            return jobSummary;
        }
    };

    Future<JobSummary> future = executor.submit(callback);
    try {
        if (queryTimeout <= 0) {
            jobSummary = future.get();
        } else {
            jobSummary = future.get(queryTimeout, TimeUnit.SECONDS);
        }
    } catch (InterruptedException e) {
        // ignore
    } catch (TimeoutException e) {
        throw new SQLException(e);
    } catch (ExecutionException e) {
        throw new SQLException(e.getCause());
    }

    if (jobSummary == null) {
        throw new SQLException("job result is null");
    }

    try {
        initColumnNamesAndTypes(jobSummary.getResultSchema());
        return clientApi.getJobResult2(job);
    } catch (ClientException e) {
        throw new SQLException(e);
    }
}

From source file:com.chiorichan.database.DatabaseEngine.java

public LinkedHashMap<String, Object> selectOne(String table, List<String> keys, List<? extends Object> values)
        throws SQLException {
    if (con == null)
        throw new SQLException("The SQL connection is closed or was never opened.");

    if (isNull(keys) || isNull(values)) {
        Loader.getLogger().warning("[DB ERROR] Either keys array or values array equals null!\n");
        return null;
    }/*w  w  w  .j ava2 s .  c o m*/

    if (keys.size() != values.size()) {
        System.err.print("[DB ERROR] Keys array and values array must match in length!\n");
        return null;
    }

    LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();

    String where = "";

    if (keys.size() > 0 && values.size() > 0) {
        int x = 0;
        String prefix = "";
        for (String s : keys) {
            where += prefix + "`" + s + "` = '" + values.get(x) + "'";
            x++;
            prefix = " AND ";
        }
    }

    ResultSet rs = query("SELECT * FROM `" + table + "` WHERE " + where + " LIMIT 1;");

    if (rs != null && getRowCount(rs) > 0) {
        try {
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();

            do {
                for (int i = 1; i < columnCount + 1; i++) {
                    result.put(rsmd.getColumnName(i), rs.getObject(i));
                }
            } while (rs.next());

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return null;
}

From source file:it.larusba.neo4j.jdbc.http.driver.CypherExecutor.java

/**
 * Rollback the current transaction./*  w  ww .j  av  a  2  s. c o  m*/
 *
 * @throws SQLException if there is no transaction to rollback
 */
public void rollback() throws SQLException {
    if (this.getOpenTransactionId() > 0) {
        // Prepare the request
        HttpDelete request = new HttpDelete(currentTransactionUrl);
        Neo4jResponse response = this.executeHttpRequest(request);
        if (response.code != 200 & response.hasErrors()) {
            throw new SQLException(response.displayErrors());
        }
        this.currentTransactionUrl = this.transactionUrl;
    } else {
        throw new SQLException("There is no transaction to rollback");
    }
}

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

public void update(DocumentItem c, QueryRunner run, Connection conn) throws SQLException {
    PreparedStatement st = conn.prepareStatement(SQL_UPDATE_DOCUMENTITEM);
    st.setString(1, c.getPriceNetSingle());
    st.setString(2, c.getPriceGrossSingle());
    st.setString(3, c.getPriceTaxSingle());
    st.setString(4, c.getPriceNetAll());
    st.setString(5, c.getPriceGrossAll());
    st.setString(6, c.getPriceTaxAll());
    st.setString(7, c.getTaxValue());/*w  w w . j a  va  2 s  . c om*/
    st.setString(8, c.getQuantity());
    if (c.getProduct().getId().longValue() == 0 && c.getDocument_id().longValue() == 0) {
        throw new SQLException(
                "For DocumentItem corresponding product and document it belongs to need to be specified");
    }
    if (c.getProduct().getId() != 0) {
        st.setLong(9, c.getProduct().getId());
    } else {
        st.setNull(9, java.sql.Types.NUMERIC);
    }
    if (c.getDocument_id().longValue() != 0) {
        st.setLong(10, c.getDocument_id());
    } else {
        st.setNull(10, java.sql.Types.NUMERIC);
    }
    st.setString(11, c.getProduct().getName());
    st.setLong(12, c.getId());
    // run the query
    int i = st.executeUpdate();
    System.out.println("i: " + i);
    if (i == -1) {
        System.out.println("db error : " + SQL_UPDATE_DOCUMENTITEM);
    }
}